← Back to Angular, page 9

angular-0175 · Medium mid

Compare take, first, takeWhile, takeUntil and last in RxJS. Which one do you use to stop a stream, and what happens on an empty stream?

take(n) completes after n values. first() completes after the first value (or the first that matches) and errors if the source completes empty. takeWhile completes when a condition turns false. takeUntil completes when another observable emits. last emits the final value when the source completes, so it needs a source that ends.

Full answer

All of these operators complete the stream early, but they decide when in different ways.

  • take(n): emits the first n values and then completes and unsubscribes from the source. If the source completes with fewer values, you get only those. No error.
  • first() and first(predicate): emits the first value (or the first that passes the predicate) and completes. If the source completes without a matching value, it throws EmptyError (no elements in sequence), unless you give a default: first(undefined, defaultValue). Use take(1) when an empty result is acceptable.
  • takeWhile(predicate, inclusive?): emits while the predicate is true, and completes at the first false value. That value is dropped unless inclusive is true. Good for "until the progress reaches 100".
  • takeUntil(notifier$): emits until the notifier emits, and then completes. This is the classic way to stop a stream when a component is destroyed (takeUntil(this.destroy$)), now mostly replaced by takeUntilDestroyed(). The notifier must come last in the pipe, or an inner subscription created after it can leak.
  • last(): waits until the source completes and then emits the final value. On an endless source it never emits. On an empty source it throws EmptyError too.
  • skip, skipWhile and skipUntil are the matching operators that ignore values at the start.

Common uses:

  • HTTP: http.get already completes, so you do not need take(1).
  • store.select(...).pipe(first()) or take(1) to read the current value once.
  • A countdown with interval(1000).pipe(take(5)).
  • A polling loop with takeWhile(status => status !== 'done', true) (inclusive, so the final status is also emitted).

Completion matters because complete runs the teardown logic and lets forkJoin, concat and toArray finish. A stream that never completes can hold memory and subscriptions.

typescript
import { EMPTY, first, from, last, take, takeUntil, takeWhile, timer, interval, lastValueFrom } from 'rxjs';

const nums$ = from([1, 2, 3, 4, 5]);
const show = (label: string) => ({
  next: (v: unknown) => console.log(label, 'next', v),
  error: (e: Error) => console.log(label, 'error', e.name),
  complete: () => console.log(label, 'complete'),
});

nums$.pipe(take(2)).subscribe(show('take(2)'));
nums$.pipe(first((n) => n > 3)).subscribe(show('first(>3)'));
nums$.pipe(takeWhile((n) => n < 3)).subscribe(show('takeWhile(<3)'));
nums$.pipe(takeWhile((n) => n < 3, true)).subscribe(show('takeWhile inclusive'));
nums$.pipe(last()).subscribe(show('last'));

EMPTY.pipe(take(1)).subscribe(show('empty take(1)'));
EMPTY.pipe(first()).subscribe(show('empty first()'));
EMPTY.pipe(first(undefined, 0)).subscribe(show('empty first(default)'));

interval(10).pipe(takeUntil(timer(35))).subscribe(show('takeUntil'));
lastValueFrom(nums$).then((v) => console.log('lastValueFrom', v));

RxJS 7.8. The script was run in Node 24 twice with identical output. It prints the results for a normal stream and for an empty stream.

Key points

  • `take(n)` is silent on short sources. `first()` errors on an empty source. `last()` needs completion.
  • `takeWhile` stops at the first false value (use `inclusive` to emit it). `takeUntil` stops on a notifier.
  • Put `takeUntil` last in the pipe. Prefer `takeUntilDestroyed()` in components.
  • Early completion runs teardown and lets other operators finish.

Common mistakes

  • Using `first()` when the source may be empty.
  • Putting `takeUntil` before `switchMap`, which can leak the inner subscription.
  • Expecting `last()` to work on an endless stream.

Follow-ups

  • What does `takeWhile(fn, true)` change?
  • How is `take(1)` different from `first()`?
  • Why is the position of `takeUntil` important?

Tips

  • Give the empty stream behaviour of each operator.
  • Mention `takeUntilDestroyed` as the modern choice.
  • Use a polling example for `takeWhile`.

Evaluation rubric

  • Describes each operator's stopping rule.
  • Knows the empty stream and error cases.
  • Applies them to realistic cases.