first

take

accepts 1 input stream, an amount

  • When the input stream emits its n-th value:
    • if n < amount, the value is emitted
    • if n == amount, the value is emitted and the stream immediately completes

returns a new stream of at most amount values

first

accepts 1 input stream, a predicate (optional)

  • When the input stream emits a first value, the output stream:
    • emits this first value
    • and immediately completes

returns a new stream emitting only the first value

Published on Monday, 22 Jan. 2018
Revised on Monday, 8 Oct. 2018

In RxJS, first accepts an optional predicate. Learn more ➜
Read more about stream completion ➜

Take vs First

Question: Do ❚ take(1) and ❚ first() return the same stream of events?

Answer: Clearly, they return the same stream of events when the input stream emits at least one event. But the results may be different if the input stream emits no value before its completion (I’ll detail such edge cases in a future article).

Last vs First

❚ last (seen in Episode 10) is the counterpart of ❚ first:

Question: Are ❚ last and ❚ first outputs identical when the input stream emits only one value?




Answer: Not when the input stream emits only one value and completes later or never completes. ❚ first and ❚ last are not strictly “symmetrical”. Remember that ❚ last has to wait for the ◉ complete notification (read more about stream completion).

Quick Exercises

Given a stream of numbers, return a stream that emits only the first even number and completes immediately. For example, given the stream 1 1 1 0 1 0 0 1, emit only the first 0.

And what about emitting the last even number?

See also


takeWhile vs skipWhile

Cédric Soulas Follow Hire me

Freelance Developer Advocate. Motion graphics with code. JavaScript and Elm. cedricsoulas.com

Subscribe to reactive.how newsletter

Join the Newsletter

Learn Reactive Programming and stay up-to-date:

Receive my latest news, product updates and programming visualizations. You can unsubscribe at any time.

Highlights

@CedricSoulas

Making an illustrated book!

The Illustrated Book of RxJS

Learn more →