highlight.js

Thursday, September 2, 2021

How to Efficiently Wait for RxJava Observer to Complete?

Almost all tutorials including the RxJava official ones deliver a message to RxJava developers that Thread.sleep(...) is recommended in testing RxJava code snippets. However, that is not efficient enough.

Here is an alternative way for your reference.
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
ExecutorService executorService = Executors.newFixedThreadPool(4);
Observable.timer(10, TimeUnit.MILLISECONDS, Schedulers.from(executorService))
        .subscribe(t -> atomicBoolean.set(true));
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
assertTrue(atomicBoolean.get());
The key is to inject a custom thread pool and wait for that thread pool to complete.

No comments:

Post a Comment

Cue Club 2 on Apple Silicon

It's been quite a long time for me not to play a decent snooker game since I replaced my Windows laptop with an Apple Silicon one. To be...