Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava 2.0 - how to combine Observable and Completable

Tags:

java

rx-java2

Say there is interface containing methods:

Observable<Data> makeHttpCall(int param1, boolean param2);

Completable storeInDatabase(Data data);

Completable combinedCall(int param1, boolean param2);

What is the best way to implement the combinedCall method that would:

  1. fetch data from makeHttpCall
  2. store it using storeInDatabase
  3. return Completable that completes when storeInDatabase completes?

Seems that in RxJava 1.0 it was possible to do Completable.merge(Observable) but merge does not seem to accept Observable any more.

like image 391
Martin G. Avatar asked Sep 14 '26 10:09

Martin G.


1 Answers

First of all I don't believe merge is a good fit for your needs, as the storeInDatabase has to be performed on the results of makeHttpCall instead of parallel to it.

This should work for you:

Completable combinedCall(int param1, boolean param2) {
    return makeHttpCall(param1, param2)
            .flatMapCompletable(new Function<Data, CompletableSource>() {
                @Override
                public CompletableSource apply(@NonNull Data d) throws Exception {
                    return storeInDatabase(d);
                }
            });
}
like image 83
Bartek Lipinski Avatar answered Sep 15 '26 22:09

Bartek Lipinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!