Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until JavaRx2 Flowable will finish all its tasks?

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.

like image 735
Alex Avatar asked Dec 04 '25 16:12

Alex


1 Answers

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));
like image 162
Ricard Kollcaku Avatar answered Dec 06 '25 05:12

Ricard Kollcaku