2.0-alpha Menu

take(count) vs takeWhile(predicate) in RxJS


This is how ❚ take operates with a maximum amount of events to emit:

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

It returns a new stream of at most amount values.


This is how ❚ takeWhile operates with a predicate:

  • Each event value of the input stream is given to the predicate:
    • If the predicate returns ✔ true, the event can pass
    • Otherwise, the event is ignored and the stream immediately completes


In the animation above, can you spot the difference between the outputs? Can you explain why?

Answer: the ◉ complete notification happens at a different moment:

  • On the one hand, ❚ take returns a stream that emits at most amount values and can complete as soon as this amount is reached.
  • On the other hand, ❚ takeWhile has to wait for the predicate to return ✘ false in order to complete.

See also

take(1) vs first()

takeLast vs take

Can you fill in the blanks?

Project vs Predicate functions

💌 I create something new each week!
Learn Reactive Programming and stay tuned.

Occasional updates, plus:

Cédric Soulas - Freelance Developer Advocate. Learn more.

Follow 👨‍💻 Hire me