Home » RxJS expand() Transformation Operator

RxJS expand() Transformation Operator

by Online Tutorials Library

RxJS expand() Transformation Operator

RxJS expand() operator is a transformation operator that recursively projects each source value to an Observable, which is later merged into the output Observable. The final value is observable. It is similar to mergeMap, but the difference is that it applies the projection function to every source value and every output value. It’s recursive.

It takes three arguments, the project function, the concurrency, and the optional scheduler object.

Syntax:

Following is the syntax of the expand() operator:

Parameter Explanation

  • It is a function that applies to the items emitted by the source Observable or the output Observable and returns a new Observable.
  • concurrent: It is an optional argument. It specifies the maximum number of input Observables being subscribed to concurrently. Its default value is Number.POSITIVE_INFINITY.
  • scheduler: It is also an optional argument. It is a scheduler that is used at the time of the emission of values. Its default value is undefined.

Return value

The expand() operator’s return value is an observable that emits the source values and returns the result of applying the projection function and merging the results of the Observables obtained from this transformation.

Let us see some examples of expand() operator to understand it clearly.

Example 1

Output:

After executing the above example, you will see the following result:

RxJS expand() Transformation Operator

In the above example, we have the of(1, 2, 3, 4, 5) Observable, which have the emitted values which piped to the expand(x => of(x).pipe(delay(1000))) Observable. After that it recieves 10 values from the Observable returned by expand, which takes the of(1, 2, 3, 4, 5) Observable’s emitted values and emit them repeatedly until get the 10 values. Each group is emitted after waiting 1 second.

Here, the pipe(delay(1000)) is responsible for delaying the emission of each group of values.

Example 2 (Add one for each invocation)

Output:

After executing the above example, you will see the following result:

RxJS expand() Transformation Operator


Next TopicRxJS Operators

You may also like