bufferToggle

签名: bufferToggle(openings: Observable, closingSelector: Function): Observable

开启开关以捕获源 observable 所发出的值,关闭开关以将缓冲的值作为数组发出。

bufferToggle - 图1

示例

示例 1: 使用 interval 来切换缓冲的开关

( StackBlitz | jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { bufferToggle } from 'rxjs/operators';
  3. // 每1秒发出值
  4. const sourceInterval = interval(1000);
  5. // 5秒后开启第一个缓冲区,然后每5秒钟开启新的缓冲区
  6. const startInterval = interval(5000);
  7. // 3秒后发出值以关闭相应的缓冲区
  8. const closingInterval = val => {
  9. console.log(`Value ${val} emitted, starting buffer! Closing in 3s!`);
  10. return interval(3000);
  11. };
  12. // 每5秒会开启一个新的缓冲区以收集发出的值,3秒后发出缓冲的值
  13. const bufferToggleInterval = sourceInterval.pipe(
  14. bufferToggle(
  15. startInterval,
  16. closingInterval
  17. )
  18. );
  19. // 输出到控制台
  20. // 输出: Emitted Buffer: [4,5,6]...[9,10,11]
  21. const subscribe = bufferToggleInterval.subscribe(val =>
  22. console.log('Emitted Buffer:', val)
  23. );

其他资源


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