How to callback only if the previous observable returns a specific value

Suppose I have 3 functions, each returning an observable. Each observable will emit only one value - true

or false

. I want to call them one by one only if the previous one returns true

. Otherwise, I just want to return false

and end the observable. How can i do this?

It would be easy with promises:

return fn1().then(fn2).then(fn3).catch((v)=>{return v})

      

Once any function in the chain rejects the promise with a help false

, no other invocation calls will be called and the value of the resolved promise will be false

. I'm looking for something similar with observables.

+3


source to share


1 answer


You can use concatMap()

to execute async tasks in order, and then takeWhile()

terminate the thread if needed:



fn1()
  .takeWhile(res => res)
  .concatMap(() => fn2())
  .takeWhile(res => res)
  .concatMap(() => fn3())
  .takeWhile(res => res)
  .subscribe(...)

      

+2


source







All Articles