Debian Codegraph @

src/test/java/io/reactivex/rxjava3/internal/operators/observable/BlockingObservableNextTest.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.*;
19 import java.util.concurrent.*;
20 import java.util.concurrent.atomic.*;
21
22 import org.junit.*;
23
24 import io.reactivex.rxjava3.core.*;
25 import io.reactivex.rxjava3.core.Observable;
26 import io.reactivex.rxjava3.core.Observer;
27 import io.reactivex.rxjava3.disposables.*;
28 import io.reactivex.rxjava3.exceptions.TestException;
29 import io.reactivex.rxjava3.internal.operators.observable.BlockingObservableNext.NextObserver;
30 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
31 import io.reactivex.rxjava3.schedulers.Schedulers;
32 import io.reactivex.rxjava3.subjects.*;
33 import io.reactivex.rxjava3.testsupport.TestHelper;
34
35 public class BlockingObservableNextTest extends RxJavaTest {
36
37 private void fireOnNextInNewThread(final Subject<String> o, final String value) {
38 new Thread() {
39 @Override
40 public void run() {
41 try {
42 Thread.sleep(500);
43 } catch (InterruptedException e) {
44 // ignore
45 }
46 o.onNext(value);
47 }
48 }.start();
49 }
50
51 private void fireOnErrorInNewThread(final Subject<String> o) {
52 new Thread() {
53 @Override
54 public void run() {
55 try {
56 Thread.sleep(500);
57 } catch (InterruptedException e) {
58 // ignore
59 }
60 o.onError(new TestException());
61 }
62 }.start();
63 }
64
65 static <T> Iterable<T> next(ObservableSource<T> source) {
66 return new BlockingObservableNext<>(source);
67 }
68
69 @Test
70 public void next() {
71 Subject<String> obs = PublishSubject.create();
72 Iterator<String> it = next(obs).iterator();
73 fireOnNextInNewThread(obs, "one");
74 assertTrue(it.hasNext());
75 assertEquals("one", it.next());
76
77 fireOnNextInNewThread(obs, "two");
78 assertTrue(it.hasNext());
79 assertEquals("two", it.next());
80
81 fireOnNextInNewThread(obs, "three");
82 try {
83 assertEquals("three", it.next());
84 } catch (NoSuchElementException e) {
85 fail("Calling next() without hasNext() should wait for next fire");
86 }
87
88 obs.onComplete();
89 assertFalse(it.hasNext());
90 try {
91 it.next();
92 fail("At the end of an iterator should throw a NoSuchElementException");
93 } catch (NoSuchElementException e) {
94 }
95
96 // If the Observable is completed, hasNext always returns false and next always throw a NoSuchElementException.
97 assertFalse(it.hasNext());
98 try {
99 it.next();
100 fail("At the end of an iterator should throw a NoSuchElementException");
101 } catch (NoSuchElementException e) {
102 }
103 }
104
105 @Test
106 public void nextWithError() {
107 Subject<String> obs = PublishSubject.create();
108 Iterator<String> it = next(obs).iterator();
109 fireOnNextInNewThread(obs, "one");
110 assertTrue(it.hasNext());
111 assertEquals("one", it.next());
112
113 fireOnErrorInNewThread(obs);
114 try {
115 it.hasNext();
116 fail("Expected an TestException");
117 } catch (TestException e) {
118 }
119
120 assertErrorAfterObservableFail(it);
121 }
122
123 @Test
124 public void nextWithEmpty() {
125 Observable<String> obs = Observable.<String> empty().observeOn(Schedulers.newThread());
126 Iterator<String> it = next(obs).iterator();
127
128 assertFalse(it.hasNext());
129 try {
130 it.next();
131 fail("At the end of an iterator should throw a NoSuchElementException");
132 } catch (NoSuchElementException e) {
133 }
134
135 // If the Observable is completed, hasNext always returns false and next always throw a NoSuchElementException.
136 assertFalse(it.hasNext());
137 try {
138 it.next();
139 fail("At the end of an iterator should throw a NoSuchElementException");
140 } catch (NoSuchElementException e) {
141 }
142 }
143
144 @Test
145 public void onError() throws Throwable {
146 Subject<String> obs = PublishSubject.create();
147 Iterator<String> it = next(obs).iterator();
148
149 obs.onError(new TestException());
150 try {
151 it.hasNext();
152 fail("Expected an TestException");
153 } catch (TestException e) {
154 // successful
155 }
156
157 assertErrorAfterObservableFail(it);
158 }
159
160 @Test
161 public void onErrorInNewThread() {
162 Subject<String> obs = PublishSubject.create();
163 Iterator<String> it = next(obs).iterator();
164
165 fireOnErrorInNewThread(obs);
166
167 try {
168 it.hasNext();
169 fail("Expected an TestException");
170 } catch (TestException e) {
171 // successful
172 }
173
174 assertErrorAfterObservableFail(it);
175 }
176
177 private void assertErrorAfterObservableFail(Iterator<String> it) {
178 // After the Observable fails, hasNext and next always throw the exception.
179 try {
180 it.hasNext();
181 fail("hasNext should throw a TestException");
182 } catch (TestException e) {
183 }
184 try {
185 it.next();
186 fail("next should throw a TestException");
187 } catch (TestException e) {
188 }
189 }
190
191 @Test
192 public void nextWithOnlyUsingNextMethod() {
193 Subject<String> obs = PublishSubject.create();
194 Iterator<String> it = next(obs).iterator();
195 fireOnNextInNewThread(obs, "one");
196 assertEquals("one", it.next());
197
198 fireOnNextInNewThread(obs, "two");
199 assertEquals("two", it.next());
200
201 obs.onComplete();
202 try {
203 it.next();
204 fail("At the end of an iterator should throw a NoSuchElementException");
205 } catch (NoSuchElementException e) {
206 }
207 }
208
209 @Test
210 public void nextWithCallingHasNextMultipleTimes() {
211 Subject<String> obs = PublishSubject.create();
212 Iterator<String> it = next(obs).iterator();
213 fireOnNextInNewThread(obs, "one");
214 assertTrue(it.hasNext());
215 assertTrue(it.hasNext());
216 assertTrue(it.hasNext());
217 assertTrue(it.hasNext());
218 assertEquals("one", it.next());
219
220 obs.onComplete();
221 try {
222 it.next();
223 fail("At the end of an iterator should throw a NoSuchElementException");
224 } catch (NoSuchElementException e) {
225 }
226 }
227
228 /**
229 * Confirm that no buffering or blocking of the Observable onNext calls occurs and it just grabs the next emitted value.
230 * <p>
231 * This results in output such as {@code => a: 1 b: 2 c: 89}
232 *
233 * @throws Throwable some method call is declared throws
234 */
235 @Test
236 public void noBufferingOrBlockingOfSequence() throws Throwable {
237 int repeat = 0;
238 for (;;) {
239 final SerialDisposable task = new SerialDisposable();
240 try {
241 final CountDownLatch finished = new CountDownLatch(1);
242 final int COUNT = 30;
243 final CountDownLatch timeHasPassed = new CountDownLatch(COUNT);
244 final AtomicBoolean running = new AtomicBoolean(true);
245 final AtomicInteger count = new AtomicInteger(0);
246 final Observable<Integer> obs = Observable.unsafeCreate(new ObservableSource<Integer>() {
247
248 @Override
249 public void subscribe(final Observer<? super Integer> o) {
250 o.onSubscribe(Disposable.empty());
251 task.replace(Schedulers.single().scheduleDirect(new Runnable() {
252
253 @Override
254 public void run() {
255 try {
256 while (running.get() && !task.isDisposed()) {
257 o.onNext(count.incrementAndGet());
258 timeHasPassed.countDown();
259 }
260 o.onComplete();
261 } catch (Throwable e) {
262 o.onError(e);
263 } finally {
264 finished.countDown();
265 }
266 }
267 }));
268 }
269
270 });
271
272 Iterator<Integer> it = next(obs).iterator();
273
274 assertTrue(it.hasNext());
275 int a = it.next();
276 assertTrue(it.hasNext());
277 int b = it.next();
278 // we should have a different value
279 assertTrue("a and b should be different", a != b);
280
281 // wait for some time (if times out we are blocked somewhere so fail ... set very high for very slow, constrained machines)
282 timeHasPassed.await(8000, TimeUnit.MILLISECONDS);
283
284 assertTrue(it.hasNext());
285 int c = it.next();
286
287 assertTrue("c should not just be the next in sequence", c != (b + 1));
288 assertTrue("expected that c [" + c + "] is higher than or equal to " + COUNT, c >= COUNT);
289
290 assertTrue(it.hasNext());
291 int d = it.next();
292 assertTrue(d > c);
293
294 // shut down the thread
295 running.set(false);
296
297 finished.await();
298
299 assertFalse(it.hasNext());
300
301 System.out.println("a: " + a + " b: " + b + " c: " + c);
302 break;
303 } catch (AssertionError ex) {
304 if (++repeat == 3) {
305 throw ex;
306 }
307 Thread.sleep((int)(1000 * Math.pow(2, repeat - 1)));
308 } finally {
309 task.dispose();
310 }
311 }
312 }
313
314 @Test
315 public void singleSourceManyIterators() throws InterruptedException {
316 Observable<Long> o = Observable.interval(250, TimeUnit.MILLISECONDS);
317 PublishSubject<Integer> terminal = PublishSubject.create();
318 Observable<Long> source = o.takeUntil(terminal);
319
320 Iterable<Long> iter = source.blockingNext();
321
322 for (int j = 0; j < 3; j++) {
323 BlockingObservableNext.NextIterator<Long> it = (BlockingObservableNext.NextIterator<Long>)iter.iterator();
324
325 for (long i = 0; i < 10; i++) {
326 Assert.assertTrue(it.hasNext());
327 Assert.assertEquals(j + "th iteration next", Long.valueOf(i), it.next());
328 }
329 terminal.onNext(1);
330 }
331 }
332
333 @Test
334 public void synchronousNext() {
335 assertEquals(1, BehaviorSubject.createDefault(1).take(1).blockingSingle().intValue());
336 assertEquals(2, BehaviorSubject.createDefault(2).blockingIterable().iterator().next().intValue());
337 assertEquals(3, BehaviorSubject.createDefault(3).blockingNext().iterator().next().intValue());
338 }
339
340 @Test
341 public void interrupt() {
342 Iterator<Object> it = Observable.never().blockingNext().iterator();
343
344 try {
345 Thread.currentThread().interrupt();
346 it.next();
347 } catch (RuntimeException ex) {
348 assertTrue(ex.toString(), ex.getCause() instanceof InterruptedException);
349 }
350 }
351
352 @Test(expected = UnsupportedOperationException.class)
353 public void remove() {
354 Observable.never().blockingNext().iterator().remove();
355 }
356
357 @Test
358 public void nextObserverError() {
359 NextObserver<Integer> no = new NextObserver<>();
360
361 List<Throwable> errors = TestHelper.trackPluginErrors();
362 try {
363 no.onError(new TestException());
364
365 TestHelper.assertUndeliverable(errors, 0, TestException.class);
366 } finally {
367 RxJavaPlugins.reset();
368 }
369 }
370
371 @Test
372 public void nextObserverOnNext() throws Exception {
373 NextObserver<Integer> no = new NextObserver<>();
374
375 no.setWaiting();
376 no.onNext(Notification.createOnNext(1));
377
378 no.setWaiting();
379 no.onNext(Notification.createOnNext(1));
380
381 assertEquals(1, no.takeNext().getValue().intValue());
382 }
383
384 @Test
385 public void nextObserverOnCompleteOnNext() throws Exception {
386 NextObserver<Integer> no = new NextObserver<>();
387
388 no.setWaiting();
389 no.onNext(Notification.<Integer>createOnComplete());
390
391 no.setWaiting();
392 no.onNext(Notification.createOnNext(1));
393
394 assertTrue(no.takeNext().isOnComplete());
395 }
396 }