Learn RxJS
Search…
partition

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

Split one observable into two based on provided predicate.

Examples

Example 1: Split even and odd numbers
1
// RxJS v6+
2
import { from, merge } from 'rxjs';
3
import { partition, map } from 'rxjs/operators';
4
5
const source = from([1, 2, 3, 4, 5, 6]);
6
//first value is true, second false
7
const [evens, odds] = source.pipe(partition(val => val % 2 === 0));
8
/*
9
Output:
10
"Even: 2"
11
"Even: 4"
12
"Even: 6"
13
"Odd: 1"
14
"Odd: 3"
15
"Odd: 5"
16
*/
17
const subscribe = merge(
18
evens.pipe(map(val => `Even: ${val}`)),
19
odds.pipe(map(val => `Odd: ${val}`))
20
).subscribe(val => console.log(val));
Copied!
Example 2: Split success and errors
1
// RxJS v6+
2
import { merge, of, from } from 'rxjs';
3
import { map, partition, catchError } from 'rxjs/operators';
4
5
const source = from([1, 2, 3, 4, 5, 6]);
6
//if greater than 3 throw
7
const example = source.pipe(
8
map(val => {
9
if (val > 3) {
10
throw `${val} greater than 3!`;
11
}
12
return { success: val };
13
}),
14
catchError(val => of({ error: val }))
15
);
16
//split on success or error
17
const [success, error] = example.pipe(partition(res => res.success));
18
/*
19
Output:
20
"Success! 1"
21
"Success! 2"
22
"Success! 3"
23
"Error! 4 greater than 3!"
24
*/
25
const subscribe = merge(
26
success.pipe(map(val => `Success! ${val.success}`)),
27
error.pipe(map(val => `Error! ${val.error}`))
28
).subscribe(val => console.log(val));
Copied!
Example 3: (v6.5+) Partition as a static function
1
// RxJS v6.5+
2
import { merge, of, from, partition } from 'rxjs';
3
import { map, catchError } from 'rxjs/operators';
4
5
const source = from([1, 2, 3, 4, 5, 6]);
6
//if greater than 3 throw
7
const example = source.pipe(
8
map(val => {
9
if (val > 3) {
10
throw `${val} greater than 3!`;
11
}
12
return { success: val };
13
}),
14
catchError(val => of({ error: val }))
15
);
16
// split on success or error
17
const [success, error] = partition(example, res => res.success);
18
/*
19
Output:
20
"Success! 1"
21
"Success! 2"
22
"Success! 3"
23
"Error! 4 greater than 3!"
24
*/
25
const subscribe = merge(
26
success.pipe(map(val => `Success! ${val.success}`)),
27
error.pipe(map(val => `Error! ${val.error}`))
28
).subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 1yr ago