Take, TakeUntil, TakeWhile & TakeLast In Angular

Take, TakeUntil, TakeWhile & TakeLast In Angular

In this article, we will learn about taking, TakeUntil, TakeWhile & TakeLast in Angular. The words "take," "takeUntil," "takeWhile" and "take" are all synonyms for "take". The last operations allow us to filter out the observable's emitted values. take(n) returns the first n values, while takeLast(n) returns the last n. Until it is alerted to cease, the takeUntil(notifier) emits the values. While values satisfy the predicate, takeWhile(predicate) emits the value. When you're finished, all of the lights will turn off.

Take

Before completion, the take operator emits the first n values. Any values set as reminders are disregarded.

Syntax

take(n)

The maximum number of values to emit is n.

Take emits only n values and completes if the source emits more than n values.

If the source emits fewer than n values, then take emits them all before finishing.

Example

import { Component, VERSION } from "@angular/core";
import { of } from "rxjs";
import { take } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  
  obs = of(1, 2, 3, 4, 5).pipe(take(2));
 
  ngOnInit() {
    this.obs.subscribe(val => console.log(val));
  }
}
 
 
 
****Console ******
1
2


export class AppComponent {
 
  takeFive = interval(1000).pipe(take(5));
 
  ngOnInit() {
    this.takeFive.subscribe(val => console.log(val));
  }
}
 
 
****Console ******
0
1
2
3
4

TakeUntil

Until the notifier Observable emits a value, the takeUntil operator returns an Observable that emits a value from the source Observable.

Syntax

TakeUntil(notifier: Observable): Observable

The TakeUntil Operator requires a notifier observable as a parameter.

TakeUntil emits the values from the Source Observable as long as the notifier observable does not get any value.

The TakeUntil completes the Source observable when the notifier emits a value.

If the notifier finishes without emitting any values, the TakeUntil continues to emit values from the source until the source finishes.

Example

We create a notifier observable in the example below.

notifier= new Subject();

When the stop button is pressed, the notifier observable emits a value.

stopObs() {
  this.notifier.next();
  this.notifier.complete();
}

As seen below, use the takeUntil method in the source observable.

obs = interval(1000).pipe(takeUntil(this.notifier));

Run the app. When you press the stop button, the source observable comes to a halt.

import { Component, VERSION } from "@angular/core";
import { of, interval, Subject, Observable } from "rxjs";
import { take, takeUntil, tap } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  notifier = new Subject();
 
  obs = interval(1000).pipe(takeUntil(this.notifier));
 
  ngOnInit() {
    this.obs.subscribe(val => console.log(val));
  }
 
  stopObs() {
    this.notifier.next();
    this.notifier.complete();
  }
}


<h1>TakeUntil Example</h1>
 
<button click="" stopobs="">Stop</button>
<br />

TakeUntil can be used to automatically unsubscribe all of the observables. You may find it in the Unsubscribing from an Observable lesson.

TakeWhile

As long as they pass the supplied condition, the TakeWhile operator will keep emitting the value from the source observable (predicate). It completes the observable when it receives a value that does not satisfy the criterion. Even if the values satisfy the criterion, no more values are sent.

Syntax

takeWhile(predicate: function(value, index): boolean,
inclusive?: boolean): Observable

The condition is the predicate.

If inclusive is true, before terminating the observable, it broadcasts the value that does not pass the criterion.

Example

TakeWhile tests the condition Val 3 against the incoming values in the code below. The observable completes when it receives the value 3, which does not satisfy the criteria. Despite the fact that the stream still contains values that satisfy the criterion, it does not emit any more values.

import { Component, VERSION } from "@angular/core";
import { of, interval, Subject, Observable } from "rxjs";
import { take, takeUntil, takeWhile, tap } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  obs = of(1, 2, 3, 1, 2, 3, 1, 2, 3)
    .pipe(
      takeWhile(val => val &lt; 3)
    );
 
  ngOnInit() {
    this.obs.subscribe(val => console.log(val));
  }
}
 
 
*** Console ***
1
2

Takewhile emits the number 3 before completing the observable when inclusive is set to true.

export class AppComponent {
  obs = of(1, 2, 3, 1, 2, 3, 1, 2, 3)
    .pipe(
       takeWhile(val => val &lt; 3, true)
    );
 
  ngOnInit() {
    this.obs.subscribe(val => console.log(val));
  }
}
 
*** Console ***
1
2
3

Example

evenNumbers = of(2, 4, 6, 3, 8)
  .pipe(takeWhile(n => n % 2 == 0))
  .subscribe(val => console.log(val));
 
**Console ***
2
4
6
 
//8 is not emitted

TakeWhile Vs Filter

The condition is used by both takeWhile and filter to filter out the incoming stream. Only the matching values are allowed to pass through, while the others are discarded.

The distinction is that take

When it receives the first value that does not satisfy the criterion, it discards the rest of the stream (If the inclusive is set to true, then it also emits the last value even when it does not satisfy the condition). The observable is never stopped by the filter operator.

The filter operator in the following example does not end when it receives the value 3. However, it discards it and continues on till the stream is finished.

Example

obs = of(1, 2, 3, 1, 2, 3, 1, 2, 3)
  .pipe( 
     filter(val => val &lt; 3, true)
);

ngOnInit() {
  this.obs.subscribe(val => console.log(val));
}
 
 
***Console ****
1
2
1
2
1
2

TakeLast

The TakeLast operator returns the nth value from the source observable.

Syntax

takeLast<t>(n: number)

The maximum number of values to emit is n.

TakeLast must wait for the source to finish before getting the last n number of values. As a result, if the source never finishes, TakeLast will never emit a value.

When the stream is finished, the takeLast will be called.
  1. emits the most recent n values
  2. If the source produces less than n values, it produces all of them.
  3. The stream is finished right away.
import { Component, VERSION } from "@angular/core";
import { of, range, Observable } from "rxjs";
import { takeLast } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  obs = range(1, 100).pipe(takeLast(3));
 
  ngOnInit() {
    this.obs.subscribe(val => console.log(val));
  }
}
 
***Console****
98
99
100

Conclusion

In this article, we learned what is Take, TakeUntil, TakeWhile & TakeLast and how to use them in Angular using examples.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post