RxJs takeUntil and takeWhile operators

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.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.