Our Rxjs operators of the week are takeUntil
and takeWhile
. These operators are the opposite of skipWhile
covered last week: They let the values from the source Observable pass through until a condition is met.
takeUntil
is based on a second Observable and stops emitting values when that second Observable emits for the first time, as illustrated in this marble diagram:
takeWhile
is very similar but uses a predicate instead of an Observable to decide when to stop emitting from the source Observable:
The primary use case for takeUntil
with Angular is to automate unsubscriptions from Observables, even though I recommend less verbose approaches to automating unsubscriptions, such as using the async pipe :
The above code uses a subject to emit a value when the component gets destroyed, thanks to the ngOnDestroy lifecycle hook. Then, that same subject is used by takeUntil
to complete the source Observable.
Here is a different example of takeUntil
in action on Stackblitz.