只在一系列事件发出后才会发出?

时间:2017-04-03 15:08:38

标签: rxjs

我正在尝试做类似以下的事情 - B是独立于A发射的,但我想在A之后发生B(按此顺序)时发射。

----A--------A-->
B--B--B--B----B->

------B-------B->

谢谢!

1 个答案:

答案 0 :(得分:4)

如果您有热观察并且想要从B发出值,那么您可能希望将switchMap与{{1}结合使用} :(基本上只有最后3行相关,上半部分只是模拟一些数据流)



take(1)

// Mocking A and B
const streamA$ = Rx.Observable
  .interval(2500)
  .do(() => console.log("Emitting on A => TAKE NEXT B!!!"))
  .share();
const streamB$ = Rx.Observable
  .interval(1200)
  .do(data => console.log("Emitting on B: " + data))
  .publish();
streamB$.connect();
// \End of mocking

streamA$
  .switchMap(() => streamB$.take(1))
  .subscribe(data => console.info("Took value: " + data));




如果您有冷可观察性,则可以将window<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>结合使用:

&#13;
&#13;
map
&#13;
// Mocking A and B
const streamA$ = Rx.Observable
  .interval(4000)
  .do(() => console.log("Emitting on A => TAKE NEXT B!!!"));
const streamB$ = Rx.Observable
  .interval(900)
  .do(data => console.log("Emitting on B: " + data));
// \End of mocking

streamB$.window(streamA$)
  .skip(1)                 // skip the first window, since this will be emitted before A emitted the first time
  .mergeMap(win => win.take(1)) // each window should have at most 1 emission
  
  .subscribe(data => console.info("Took value: " + data));
&#13;
&#13;
&#13;