skip to Main Content
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


  1. You need to use distinctuntilchanged operator:

    const first$ = new Subject();
    const second$ = new Subject();
    
    const combined$ = combineLatest([first$, second$]).pipe(
      distinctUntilChanged(
        (prev, curr) => prev[0] === curr[0] && prev[1] === curr[1]
      )
    );
    combined$.subscribe(([first, second]) => {
      console.log(first, second);
    });
    
    first$.next('One');
    second$.next(true);
    
    first$.next('One');
    second$.next(true);
    second$.next(false);
    
    Login or Signup to reply.
  2. 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 the distinctUntilChanged operator in your code:

    combine$ = combineLatest([this.first$, this.second$])
      .pipe(
        distinctUntilChanged((prevValues, newValues) => {
          // Compare previous values with new values
          return (
            prevValues[0] === newValues[0] &&
            prevValues[1] === newValues[1]
          );
        }),
        map(([first, second]) => {
          // Do something with the values
        })
      );
    
    

    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 returns true if they are the same and should be ignored, or false if they are different and should be processed.

    The map operator after distinctUntilChanged 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search