How to run 2 queries sequentially in a Android RxJava Observable?

后端 未结 3 770
情歌与酒
情歌与酒 2021-01-04 04:59

I want to run 2 asynchronous tasks, one followed by the other (sequentially). I have read something about ZIP or Flat, but I didn\'t understand it very well...

My pu

3条回答
  •  無奈伤痛
    2021-01-04 05:56

    Lukas Batteau's answer is best if the queries are not dependent on one another. However, if it is necessary for you obtain the data from the local SQLite query before you run the remote query (for example you need the data for the remote query params or headers) then you can start with the local observable and then flatmap it to combine the two observables after you obtain the data from the local query:

       Observable localObservable = Observable.create(...)
       localObservable.flatMap(object -> 
       {
           return Observable.zip(Observable.just(object), *create remote observable here*, 
               (localObservable, remoteObservable) -> 
               {
                   *combining function*
               });
       }).subscribe(subscriber);
    
    
    

    The flatmap function allows you to transform the local observable into a combination of the local & remote observables via the zip function. And to reiterate, the advantage here is that the two observables are sequential, and the zip function will only run after both dependent observables run.

    Furthermore, the zip function will allow you to combine observables even if the underlying objects have different types. In that case, you provide a combining function as the 3rd parameter. If the underlying data is the same type, replace the zip function with a merge.

    提交回复
    热议问题