To use the partition
function from the RxJS library in TypeScript, you will need to start by importing it from the library. This is typically done with the following line of code at the top of your file:
index.ts34 chars2 lines
Once the function is imported, you can use it to split an observable stream into two separate streams based on a predicate function. The two resulting streams will each emit values based on whether the values pass the predicate or not.
Here is an example of using partition
with an observable of numbers:
index.ts313 chars10 lines
In this example, we use Observable.from
to create an observable stream of numbers. We then use partition
to split this stream into two separate streams - one for even numbers and one for odd numbers.
The resulting evens$
and odds$
streams are then subscribed to separately using the subscribe
method. This will log each even and odd value that is emitted as the original observable is iterated over.
Note that partition
returns an array of two observables - one for the values that pass the predicate function, and one for the values that do not pass the function. In this example, we're destructuring the array to extract these two observables into separate variables for clarity.
gistlibby LogSnag