简体   繁体   中英

Exit Observable.zip in rxjava based on condition

In RXJava, I have a 2 observables which are responses from 2 downstream calls.One downstream call is a long poll call, other is a short one and returns right away. I am using the Observable.zip to combine the responses of both the responses.The below code works fine.

Observable
 .zip(observable1, observable2)
 .flatMap(update -> foo(update));

Now what I want to implement is that if the output of the short downstream call (observable1) does not content a specific value, then skip the zip ie dont wait for the output of the longer downstream call (observable2). I tried to implement it in the below way, but if the condition is true it doesn't zip with the observable2, but it does not even emit observable1 response.

Observable finalresponse = observable1
                .takeWhile(obsResponse1 ->  checkIfValueExist(obsResponse1))
                .zipWith(observable2,  (observable1, observable2) -> execute(observable1, observable2))
                .flatMap(update -> main.execute(update));

In zip there is a rule it will return only if both of streams will emit an item so what you need to do is to filter or return Observable.empty() in observable if your object is not what you expect or you can use filter

   Observable
            .zip(Observable.just(1).filter(integer -> integer==1), Observable.just(2).filter(integer -> integer==3),(integer, integer2) -> integer)
            .flatMap(update -> foo(update));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM