Skip to main content

Overview

Emits values emitted by the source Observable so long as each value satisfies the given predicate, and then completes as soon as this predicate is not satisfied.
takeWhile subscribes and begins mirroring the source Observable. Each value emitted on the source is given to the predicate function. The output Observable emits the source values until the predicate returns false.

Type Signature

function takeWhile<T>(
  predicate: (value: T, index: number) => boolean,
  inclusive: boolean = false
): MonoTypeOperatorFunction<T>

Parameters

predicate
(value: T, index: number) => boolean
required
A function that evaluates a value emitted by the source Observable and returns a boolean.
inclusive
boolean
default:"false"
When set to true the value that caused predicate to return false will also be emitted.

Returns

MonoTypeOperatorFunction<T> - A function that returns an Observable that emits values from the source Observable so long as each value satisfies the condition defined by the predicate.

Usage Examples

Basic Example

import { fromEvent, takeWhile } from 'rxjs';

const clicks = fromEvent<PointerEvent>(document, 'click');
const result = clicks.pipe(takeWhile(ev => ev.clientX > 200));

result.subscribe(x => console.log(x));
// Emits clicks while X > 200
  • take - Takes first N values
  • takeLast - Takes last N values
  • takeUntil - Takes until another Observable emits
  • skipWhile - Skips while condition is true