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?
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);
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$);