how to use the partition function from the rxjs library in typescript

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.ts
import { partition } from 'rxjs';
34 chars
2 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.ts
import { partition } from 'rxjs';
import { Observable } from 'rxjs/Observable';

const source = Observable.from([1, 2, 3, 4, 5]);

const [evens$, odds$] = partition((val: number) => val % 2 === 0)(source);

evens$.subscribe(val => console.log(`Even: ${val}`));
odds$.subscribe(val => console.log(`Odd: ${val}`));
313 chars
10 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