Debian Codegraph @

src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableUnsubscribeOnTest.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.internal.operators.observable;
15
16 import static org.junit.Assert.*;
17
18 import java.util.List;
19 import java.util.concurrent.*;
20 import java.util.concurrent.atomic.*;
21
22 import org.junit.Test;
23
24 import io.reactivex.rxjava3.annotations.NonNull;
25 import io.reactivex.rxjava3.core.*;
26 import io.reactivex.rxjava3.disposables.*;
27 import io.reactivex.rxjava3.exceptions.TestException;
28 import io.reactivex.rxjava3.functions.Action;
29 import io.reactivex.rxjava3.internal.schedulers.ImmediateThinScheduler;
30 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
31 import io.reactivex.rxjava3.schedulers.Schedulers;
32 import io.reactivex.rxjava3.testsupport.*;
33
34 public class ObservableUnsubscribeOnTest extends RxJavaTest {
35
36 @Test
37 public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnSameThread() throws InterruptedException {
38 UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler();
39 try {
40 final ThreadSubscription subscription = new ThreadSubscription();
41 final AtomicReference<Thread> subscribeThread = new AtomicReference<>();
42 Observable<Integer> w = Observable.unsafeCreate(new ObservableSource<Integer>() {
43
44 @Override
45 public void subscribe(Observer<? super Integer> t1) {
46 subscribeThread.set(Thread.currentThread());
47 t1.onSubscribe(subscription);
48 t1.onNext(1);
49 t1.onNext(2);
50 // observeOn will prevent canceling the upstream upon its termination now
51 // this call is racing for that state in this test
52 // not doing it will make sure the unsubscribeOn always gets through
53 // t1.onComplete();
54 }
55 });
56
57 TestObserverEx<Integer> observer = new TestObserverEx<>();
58
59 w.subscribeOn(uiEventLoop).observeOn(Schedulers.computation())
60 .unsubscribeOn(uiEventLoop)
61 .take(2)
62 .subscribe(observer);
63
64 observer.awaitDone(5, TimeUnit.SECONDS);
65
66 Thread unsubscribeThread = subscription.getThread();
67
68 assertNotNull(unsubscribeThread);
69 assertNotSame(Thread.currentThread(), unsubscribeThread);
70
71 assertNotNull(subscribeThread.get());
72 assertNotSame(Thread.currentThread(), subscribeThread.get());
73 // True for Schedulers.newThread()
74
75 System.out.println("unsubscribeThread: " + unsubscribeThread);
76 System.out.println("subscribeThread.get(): " + subscribeThread.get());
77 assertSame(unsubscribeThread.toString(), unsubscribeThread, uiEventLoop.getThread());
78
79 observer.assertValues(1, 2);
80 observer.assertTerminated();
81 } finally {
82 uiEventLoop.shutdown();
83 }
84 }
85
86 @Test
87 public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnDifferentThreads() throws InterruptedException {
88 UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler();
89 try {
90 final ThreadSubscription subscription = new ThreadSubscription();
91 final AtomicReference<Thread> subscribeThread = new AtomicReference<>();
92 Observable<Integer> w = Observable.unsafeCreate(new ObservableSource<Integer>() {
93
94 @Override
95 public void subscribe(Observer<? super Integer> t1) {
96 subscribeThread.set(Thread.currentThread());
97 t1.onSubscribe(subscription);
98 t1.onNext(1);
99 t1.onNext(2);
100 // observeOn will prevent canceling the upstream upon its termination now
101 // this call is racing for that state in this test
102 // not doing it will make sure the unsubscribeOn always gets through
103 // t1.onComplete();
104 }
105 });
106
107 TestObserverEx<Integer> observer = new TestObserverEx<>();
108
109 w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation())
110 .unsubscribeOn(uiEventLoop)
111 .take(2)
112 .subscribe(observer);
113
114 observer.awaitDone(1, TimeUnit.SECONDS);
115
116 Thread unsubscribeThread = subscription.getThread();
117
118 assertNotNull(unsubscribeThread);
119 assertNotSame(Thread.currentThread(), unsubscribeThread);
120
121 assertNotNull(subscribeThread.get());
122 assertNotSame(Thread.currentThread(), subscribeThread.get());
123 // True for Schedulers.newThread()
124
125 System.out.println("UI Thread: " + uiEventLoop.getThread());
126 System.out.println("unsubscribeThread: " + unsubscribeThread);
127 System.out.println("subscribeThread.get(): " + subscribeThread.get());
128 assertSame(unsubscribeThread, uiEventLoop.getThread());
129
130 observer.assertValues(1, 2);
131 observer.assertTerminated();
132 } finally {
133 uiEventLoop.shutdown();
134 }
135 }
136
137 private static class ThreadSubscription extends AtomicBoolean implements Disposable {
138
139 private static final long serialVersionUID = -5011338112974328771L;
140
141 private volatile Thread thread;
142
143 private final CountDownLatch latch = new CountDownLatch(1);
144
145 @Override
146 public void dispose() {
147 set(true);
148 System.out.println("unsubscribe invoked: " + Thread.currentThread());
149 thread = Thread.currentThread();
150 latch.countDown();
151 }
152
153 @Override public boolean isDisposed() {
154 return get();
155 }
156
157 public Thread getThread() throws InterruptedException {
158 latch.await();
159 return thread;
160 }
161 }
162
163 public static class UIEventLoopScheduler extends Scheduler {
164
165 private final Scheduler eventLoop;
166 private volatile Thread t;
167
168 public UIEventLoopScheduler() {
169
170 eventLoop = Schedulers.single();
171
172 /*
173 * DON'T DO THIS IN PRODUCTION CODE
174 */
175 final CountDownLatch latch = new CountDownLatch(1);
176 eventLoop.scheduleDirect(new Runnable() {
177
178 @Override
179 public void run() {
180 t = Thread.currentThread();
181 latch.countDown();
182 }
183
184 });
185 try {
186 latch.await();
187 } catch (InterruptedException e) {
188 throw new RuntimeException("failed to initialize and get inner thread");
189 }
190 }
191
192 @NonNull
193 @Override
194 public Worker createWorker() {
195 return eventLoop.createWorker();
196 }
197
198 public Thread getThread() {
199 return t;
200 }
201
202 }
203
204 @Test
205 public void dispose() {
206 TestHelper.checkDisposed(Observable.just(1).unsubscribeOn(Schedulers.single()));
207 }
208
209 @Test
210 public void normal() {
211 final int[] calls = { 0 };
212
213 Observable.just(1)
214 .doOnDispose(new Action() {
215 @Override
216 public void run() throws Exception {
217 calls[0]++;
218 }
219 })
220 .unsubscribeOn(Schedulers.single())
221 .test()
222 .assertResult(1);
223
224 assertEquals(0, calls[0]);
225 }
226
227 @Test
228 public void error() {
229 final int[] calls = { 0 };
230
231 Observable.error(new TestException())
232 .doOnDispose(new Action() {
233 @Override
234 public void run() throws Exception {
235 calls[0]++;
236 }
237 })
238 .unsubscribeOn(Schedulers.single())
239 .test()
240 .assertFailure(TestException.class);
241
242 assertEquals(0, calls[0]);
243 }
244
245 @Test
246 public void signalAfterDispose() {
247 List<Throwable> errors = TestHelper.trackPluginErrors();
248 try {
249 new Observable<Integer>() {
250 @Override
251 protected void subscribeActual(Observer<? super Integer> observer) {
252 observer.onSubscribe(Disposable.empty());
253 observer.onNext(1);
254 observer.onNext(2);
255 observer.onError(new TestException());
256 observer.onComplete();
257 }
258 }
259 .unsubscribeOn(Schedulers.single())
260 .take(1)
261 .test()
262 .assertResult(1);
263
264 TestHelper.assertUndeliverable(errors, 0, TestException.class);
265 } finally {
266 RxJavaPlugins.reset();
267 }
268 }
269
270 @Test
271 public void doubleOnSubscribe() {
272 TestHelper.checkDoubleOnSubscribeObservable(o -> o.unsubscribeOn(ImmediateThinScheduler.INSTANCE));
273 }
274 }