partition

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

Split one observable into two based on provided predicate.

partition - 图1

Examples

Example 1: Split even and odd numbers

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { partition, map } from 'rxjs/operators';
  3. const source = from([1, 2, 3, 4, 5, 6]);
  4. //first value is true, second false
  5. const [evens, odds] = source.pipe(partition(val => val % 2 === 0));
  6. /*
  7. Output:
  8. "Even: 2"
  9. "Even: 4"
  10. "Even: 6"
  11. "Odd: 1"
  12. "Odd: 3"
  13. "Odd: 5"
  14. */
  15. const subscribe = merge(
  16. evens.pipe(map(val => `Even: ${val}`)),
  17. odds.pipe(map(val => `Odd: ${val}`))
  18. ).subscribe(val => console.log(val));
Example 2: Split success and errors

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { of } from 'rxjs/observable/of';
  3. import { merge } from 'rxjs/observable/merge';
  4. import { map, partition, catchError } from 'rxjs/operators';
  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));

Additional Resources


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