partition

signature: partition(predicate: function: boolean, thisArg: any): [Observable, Observable]

Split one observable into two based on provided predicate.

Ultimate RxJS

Examples

Example 1: Split even and odd numbers

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { from, merge } from 'rxjs';
import { partition, map } from 'rxjs/operators';

const source = from([1, 2, 3, 4, 5, 6]);
//first value is true, second false
const [evens, odds] = source.pipe(partition(val => val % 2 === 0));
/*
  Output:
  "Even: 2"
  "Even: 4"
  "Even: 6"
  "Odd: 1"
  "Odd: 3"
  "Odd: 5"
*/
const subscribe = merge(
  evens.pipe(map(val => `Even: ${val}`)),
  odds.pipe(map(val => `Odd: ${val}`))
).subscribe(val => console.log(val));

Example 2: Split success and errors

( StackBlitz | jsBin | jsFiddle )

Example 3: (v6.5+) Partition as a static function

( StackBlitz )

Additional Resources


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/partition.ts

Last updated