takeUntil
signature: takeUntil(notifier: Observable): Observable
takeUntil(notifier: Observable): Observable
Emit values until provided observable emits.
💡 If you only need a specific number of values, try take!
Why use takeUntil
?
takeUntil
?Consider a day at your workplace: You're anticipating an important email, but you've decided that once the clock hits 5 pm, you're clocking out, regardless of whether you've received that email or not. In this RxJS analogy, the anticipation of the email is one observable, while the 5 pm clock-out time is another. The takeUntil
operator ensures you're alert for the email's potential arrival, but the moment 5 pm arrives, you stop checking (unsubscribe).
In real-world applications, think of a scenario where you're monitoring server responses on a dashboard. However, you want this monitoring to cease once a specific "Stop Monitoring" button is clicked. That's where takeUntil
shines.
In the context of Angular, takeUntil
is particularly handy for auto-unsubscribing from observables when a component is destroyed. This is achieved by leveraging the ngOnDestroy
lifecycle hook. You'd typically create a Subject
, often named destroy$
, and use it with takeUntil
:
With this setup, as soon as the ngOnDestroy
method is called (when the component is about to be destroyed), the observables using takeUntil
with the destroy$
subject will automatically unsubscribe, ensuring that no unwanted memory leaks or unexpected behavior occurs.
Examples
Example 1: Take values until timer emits
( StackBlitz | jsBin | jsFiddle )
Example 2: Take the first 5 even numbers
( StackBlitz | jsBin | jsFiddle )
Example 3: Take mouse events on mouse down until mouse up
( StackBlitz )
Related Recipes
Additional Resources
takeUntil 📰 - Official docs
takeUntil - In Depth Dev Reference
Avoiding takeUntil leaks - Angular in Depth
Stopping a stream with takeUntil 🎥 💵 - John Linquist
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/takeUntil.ts
Last updated