LiveLoveApp logo

Filtering Operators

Filtering Operators

  • Filtering operators filter emissions from the source observable

The filter Operator

of(1, 2, 3, 4, 5, 6).pipe(
  filter((value) => value % 2 === 0),
  tap(console.log)
);

The take Operator

  • Takes the first n-values
of(1, 2, 3, 4, 5, 6).pipe(take(3));

The first and last Operators

  • Either takes the first value or the last value
  • Can accept a predicate function
const values$ = of(1, 2, 3, 4, 5, 6);

values$
  .pipe(
    first((value) => value % 2 == 0),
    tap(console.log)
  )
  .subscribe();

values$.pipe(last()).subscribe();

The debounceTime Operator

  • Debounces the observable for a specified amount of time
  • Essentially, when an item is emitted, it waits n-milliseconds for another item to emit
  • If no other item gets emitted, then the item passes through
  • If an item gets emitted within the n-milliseconds window, the timer restarts
keystrokes$.pipe(debounceTime(350));

The throttleTime Operator

  • Similar to the debounceTime operator
  • Only lets one item be emitted for each n-millisecond window
clicks$.pipe(throttleTime(350));

The distinctUntilChanged Operator

  • Discards new notifications if they match the previous notification
  • Uses referential equality by default but can be supplied with a custom comparer function
of(1, 1, 1, 2, 3, 3, 4, 5, 5)
  .pipe(distinctUntilChanged())
  .subscribe(console.log);