Angular using Takeuntil RxJS Operator


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
ng new createtakeuntil
Step 2
Now we can importtakeUntilin app.component.ts
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 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.
  1. import { Observable, Subject, timer } from 'rxjs';  
After creating a subject() and import declare the RxJS timer.
  1. sub = new Subject();  
  2. rxjsuntilTimer = timer(1000, 1000);  
Now, subscribe to the RxJS timer and show the console.
  1. this.rxjsuntilTimer.pipe(takeUntil(this.sub)).subscribe(res => {  
  2.     this.timer = res;  
  3.     if (this.timer >= 10) {  
  5.         this.sub.complete();  
  6.         this.isExpired = true;  
  7.     }  
  8. })  
Step 4
Now run the application
npm start
Step 5
On successful execution of the above command, it will show the browser.
Angular Using Takeuntil RxJS Operator


After reading this, you know more about takeuntil and how to practice it in the way.

Recommended Ebook

Build A Full-stack Web Application Using Angular And Firebase

Download Now!
Similar Articles