I am trying to learn the basics of RxJava2 library and right now I am stuck at the following moment:
I have generated myFlowable via Flowable.generate(...) and now I need to wait while all the tasks will finish its execution, before I can proceed further.
This is the code to showcase the problem:
myFlowable.parallel()
.runOn(Schedulers.computation())
.map(val -> myCollection.add(val))
.sequential()
.subscribe(val -> {
System.out.println("Thread from subscribe: " + Thread.currentThread().getName());
System.out.println("Value from subscribe: " + val.toString());
});
System.out.println("Before sleep - Number of objects: " + myCollection.size());
try {
Thread.sleep(1000);
System.out.println("After sleep - Number of objects: " + myCollection.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
I run through all my tasks and add the results to collection. And if I check the collection size right after myFlowable block then it will be different, if I check it after small Thread.sleep(). Is there any way to check that all the tasks finished its execution and we can proceed further? Any help or guidance will be greatly appreciated.
As RxJava is asynchronous the java code below observable will run while the observable will run in a different thread thets why if you want to be notified if Flowable has finished emitting data you should do that in RxJava stream. for that you have an operator .doOnComplete here you have an example how to detect when stream is finished
Flowable.range(0, 100).parallel()
.runOn(Schedulers.computation())
.map(integer -> {
return integer;
})
.sequential()
.doOnComplete(() -> {
System.out.println("finished");
})
.subscribe(integer -> System.out.println(integer));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With