Problem
How to not subscribe if values are equal to the last emission
this.first$.next('one');
this.second$.next(false);
combine$ = combineLatest([this.first$, this.second$])
.pipe(map(([first, second]) => {
//do something if one of the values is different
}))
Only subscribe if one of the values is different than the previous emitted values
Example
If:
- first emission:
this.first$.next(‘one’);
this.second$.next(false); -> subscribe first values - second emission:
this.first$.next(‘one’);
this.second$.next(false); -> do not subscribe second values
If:
- first emission:
this.first$.next(‘one’);
this.second$.next(true); -> subscribe first values - second emission:
this.first$.next(‘one’);
this.second$.next(false); -> subscribe second values
2
Answers
You need to use
distinctuntilchanged
operator:Yes, you can use the
distinctUntilChanged
operator to achieve the behavior you’re looking for. This operator emits values from the source observable only if they are different from the previously emitted value. Here’s how you can use thedistinctUntilChanged
operator in your code:In this code, the
distinctUntilChanged
operator is used to filter out consecutive emitted values that are the same as the previous emission. You provide a custom comparison function that takes the previous and new values as arguments and returnstrue
if they are the same and should be ignored, orfalse
if they are different and should be processed.The
map
operator afterdistinctUntilChanged
is where you can put your logic that operates on values that have passed the distinct check. This way, you achieve your goal of processing values only when they are different from the previous emissions.