Introduction
In this article, we will learn about Angular and how to use the takeUntil RxJS Operator in order to Manage Subscriptions demonstratively.
What is TakeUntil
- The takeUntil operator is used to automatically unsubscribe from an observable.
- takeUntil begins mirroring the source Observable. It also monitors a second Observable, notifier that you provide. If the notifier emits a value, the output Observable stops mirroring the source Observable and completes. If the notifier doesn't emit any value and completes then takeUntil will pass all values.
Steps to follow:
Step 1
Create a new project setup:
ng new projectname
Example:
ng new createtakeuntil
Step 2
Now we can importtakeUntilin app.component.ts
import{takeUntil}from'rxjs/operators'
What is RXJS
- RxJS (Reactive Extensions for JavaScript) is a library for reactive programming. It uses observables that make it easier to compose asynchronous or callback-based code.
- RxJs is the backbone of Angular applications.
- RxJS uses the concept of Observables and Observers
Observables
- Observables are a source of data.
- Every time an Observables produces new values.
- It’s dangerous because memory leaks are possible in observables.
Observers is the one that uses the data and handle those values inside the subscribe operator.
What is subject
A Subject is like an Observable, but can multicast to many Observers. Subjects are like Event Emitters: they maintain a registry of many listeners.
Step 3
Now we can import of RxJS timer.
- import { Observable, Subject, timer } from 'rxjs';
After creating a subject() and import declare the RxJS timer.
- sub = new Subject();
- rxjsuntilTimer = timer(1000, 1000);
Now, subscribe to the RxJS timer and show the console.
- this.rxjsuntilTimer.pipe(takeUntil(this.sub)).subscribe(res => {
- this.timer = res;
- if (this.timer >= 10) {
- this.sub.next();
- this.sub.complete();
- this.isExpired = true;
- }
- })
Step 4
Now run the application
npm start
Step 5
On successful execution of the above command, it will show the browser.
Conclusion
After reading this, you know more about takeuntil and how to practice it in the way.