Demo:  take

The take is a filter operator that emits only the first N items from the source.

take( firstNItems)

This filter keeps emitting the source items to the output stream.

  • But, as soon as it emits the Nth item, it will add a complete notification, specifying the end of data to it's subscriber.
//emits infinite number of items
const source = timer(500, 1500);

//Filter the source to take only the first 4 items
const filterItems = take(4);

//Map the values to say 3, 2, 1 and Go(for 3).
const mapNumbers = map(v => (v==3)? "Go!": 3-v);

const output = source.pipe(filterItems, mapNumbers)
                     .subscribe(v=>console.log(v))
What is happening ?

The take is a filter operator that emits only the first N items from the source.

Let's how it works through the demo. The "timer" as our source here, is supposed to emit infinite number of integers. - Starting with 0, 1, 2, 3 and continuing so on.

But, we are interested to take only the first four items to say 3, 2 , 1 and Go:

  • We can use take(4) as our filter.
  • This filter will keep emitting the source items to the output stream.
  • For instance it emits 0, 1 and 2 immediately they arrive.
  • But, as it emits the 4th item the number 3, it also adds a "complete" notification:
  • specifying the end of data to it's subscriber.
  • Thus, the subscription ends immediately after the 4th item.