partition

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

Split one observable into two based on provided predicate.

partition - 图1

示例

示例 1: 分割偶数和奇数

( 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. // 第一个值(events)返回 true 的数字集合,第二个值(odds)是返回 false 的数字集合
  5. const [evens, odds] = source.pipe(partition(val => val % 2 === 0));
  6. /*
  7. 输出:
  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));
示例 2: 分割正常执行和错误

( 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. // 如果大于3就抛出错误
  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. // 分割正常执行或错误
  17. const [success, error] = example.pipe(partition(res => res.success));
  18. /*
  19. 输出:
  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));

其他资源


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