Index
[RxJS] Wait on something to happen before proceeding
Tested with: RxJS v7
Let’s say you have an Observable emitting values over time and you want to wait for a specific value before proceeding on something else. And you want this to only trigger once.
import { Subject } from 'rxjs';import { filter, take } from 'rxjs/operators';
const source$ = new Subject<number>();const obs$ = source$.asObservable();
const subscription = obs$ .pipe( filter((num) => num > 2), take(1) ) .subscribe((num) => console.log('Ready!'));
source$.next(1); // No outputsource$.next(2); // No outputsource$.next(3); // "Ready!" output to consolesource$.next(4); // No outputsource$.next(3); // No output
// Make sure to to call `subscription.destroy()` to dispose properly of the subscription when done.// For example, in an Angular component's `ngOnDestroy` lifecycle hook.