RxJS: How can I do an “if” with Observables?

Let's say I have two observables and one, I want to listen to changes in one observable, if the other meets a certain condition. I tried it with zip , but it seems that they will notify me only if both observables change, but I want to receive notifications for every change in the observable, if the condition of the other is true.

What I tried:

 var firstState = new Rx.BehaviorSubject(undefined); var secondState = new Rx.BehaviorSubject(undefined); Rx.Observable.zip(firstState, secondState, function (first, second) { return { first: first, second: second } }).filter(function (value) { return value.first !== undefined; }).subscribe(function (value) { // do something with value.second }); 

I noticed that there is Rx.Observable.if , but I could not get it to work.

+6
source share
2 answers

Use pausable :

 secondState .pausable(firstState.map(function (s) { return s !== undefined; })) .subscribe(function (second) { // only occurs when first is truthy }); 
+7
source

Zip literally means so. He zips up the corresponding elements in two different sequences. What you are trying to achieve can be done in many ways.

 firstState.combineLatest(secondState, function(f, d) { return f == 10 && d > 10; }).filter(function(val) { return val }) .subscribe(function(v) { console.log(v); }); firstState.onNext(10); secondState.onNext(20); 

This is one way.

0
source

Source: https://habr.com/ru/post/981961/


All Articles