'How to use filter with two Observables and return only one in rxjs
I have a part of code that checks if two observables are up to date and returns the second observable if they are:
combineLatest([$source1, $source2]).pipe(
filter(([source1, source2]) => source1.id === source2.id),
map(([_, source2]) => source2)
);
How could I simplify the code?
Solution 1:[1]
you can use iif rxjs operator, so you can subscribe to one observable or another based on a condition
combineLatest([$source1, $source2]).pipe(
mergeMap(
([s1, s2]) => iif(() => s1.id === s2.id, of(s2), EMPTY)
)
).subscribe(console.log);
Solution 2:[2]
If you want the top of your pipe to be source2 (which means you don't have any weird stream mapping), and if you want your code to read in plain english, then you can write your code like this.
emitWhenSourcesAreEqual$ = sample(
combineLatest([source1$, source2$]).pipe(
filter(([source1, source2]) => source1?.id === source2?.id)
)
);
output$ = source2$.pipe(emitWhenSourcesAreEqual$);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Fateh Mohamed |
Solution 2 | Kevin Baker |