The expand
operator in the rxjs
library is used to recursively apply a projection function to each value emitted by a source observable, while ensuring that a maximum depth is not exceeded. Here's an example of how to use it:
index.tsx433 chars18 lines
In this example, we first import the of
, expand
, and take
operators from rxjs
. We then define the projectionFn
function, which takes an input value and returns an observable that emits a value derived from the input.
Next, we create a source observable source$
that emits the value 1
. We then use the expand
operator to recursively apply the projectionFn
to each emitted value, thus creating a new observable that emits a stream of values starting from 1
and continuously adding 1
to each subsequent value. We use the take
operator to ensure that the recursion is stopped after the fifth value is emitted.
Finally, we subscribe to the final$
observable and log its values to the console. The output will be:
index.tsx10 chars6 lines
indicating that the expand
function has applied the projectionFn
function iteratively to each emitted value until the maximum depth of 5
was reached.
gistlibby LogSnag