use of io.reactivex.disposables.SerialDisposable in project RxJava by ReactiveX.
the class BlockingFlowableNextTest method testNoBufferingOrBlockingOfSequence.
/**
* Confirm that no buffering or blocking of the Observable onNext calls occurs and it just grabs the next emitted value.
* <p/>
* This results in output such as => a: 1 b: 2 c: 89
*
* @throws Throwable some method call is declared throws
*/
@Test
public void testNoBufferingOrBlockingOfSequence() throws Throwable {
int repeat = 0;
for (; ; ) {
final SerialDisposable task = new SerialDisposable();
try {
final CountDownLatch finished = new CountDownLatch(1);
final int COUNT = 30;
final CountDownLatch timeHasPassed = new CountDownLatch(COUNT);
final AtomicBoolean running = new AtomicBoolean(true);
final AtomicInteger count = new AtomicInteger(0);
final Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() {
@Override
public void subscribe(final Subscriber<? super Integer> o) {
o.onSubscribe(new BooleanSubscription());
task.replace(Schedulers.single().scheduleDirect(new Runnable() {
@Override
public void run() {
try {
while (running.get() && !task.isDisposed()) {
o.onNext(count.incrementAndGet());
timeHasPassed.countDown();
}
o.onComplete();
} catch (Throwable e) {
o.onError(e);
} finally {
finished.countDown();
}
}
}));
}
});
Iterator<Integer> it = obs.blockingNext().iterator();
assertTrue(it.hasNext());
int a = it.next();
assertTrue(it.hasNext());
int b = it.next();
// we should have a different value
assertTrue("a and b should be different", a != b);
// wait for some time (if times out we are blocked somewhere so fail ... set very high for very slow, constrained machines)
timeHasPassed.await(8000, TimeUnit.MILLISECONDS);
assertTrue(it.hasNext());
int c = it.next();
assertTrue("c should not just be the next in sequence", c != (b + 1));
assertTrue("expected that c [" + c + "] is higher than or equal to " + COUNT, c >= COUNT);
assertTrue(it.hasNext());
int d = it.next();
assertTrue(d > c);
// shut down the thread
running.set(false);
finished.await();
assertFalse(it.hasNext());
System.out.println("a: " + a + " b: " + b + " c: " + c);
break;
} catch (AssertionError ex) {
if (++repeat == 3) {
throw ex;
}
Thread.sleep((int) (1000 * Math.pow(2, repeat - 1)));
} finally {
task.dispose();
}
}
}
Aggregations