问题
I'm trying to do something like the following - B is being emitted independently of A, but I want to emit when there is a B that happens after an A (in that order).
----A--------A-->
B--B--B--B----B->
------B-------B->
Thanks!
回答1:
In case you have a hot observable and you want to emit the values from B, then you might want to use a switchMap in combination with a take(1): (basically just the 3 last lines are relevant, the upper part is just mocking some data-stream)
// 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));
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
If you have cold observables you could use window in combination with map:
// 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));
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
来源:https://stackoverflow.com/questions/43188180/emitting-only-after-set-of-events