如何使一个可观察序列等待另一个可观察序列完成然后再发射?

2022-08-30 04:59:55

假设我有一个,就像这样:Observable

var one = someObservable.take(1);

one.subscribe(function(){ /* do something */ });

然后,我有第二个:Observable

var two = someOtherObservable.take(1);

现在,我想这样做,但我想确保在订阅者被解雇之前已经完成了。subscribe()twoonetwo

我可以使用哪种缓冲方法来使第二个等待第一个缓冲完成?two

我想我正在寻求暂停,直到完成。twoone


答案 1

我能想到的几种方法

import {take, publish} from 'rxjs/operators'
import {concat} from 'rxjs'

//Method one

var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1));
concat(one, two).subscribe(function() {/*do something */});

//Method two, if they need to be separate for some reason
var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1), publish());
two.subscribe(function(){/*do something */});
one.subscribe(function(){/*do something */}, null, two.connect.bind(two));

答案 2

如果要确保保留执行顺序,可以使用 flatMap,如以下示例所示

const first = Rx.Observable.of(1).delay(1000).do(i => console.log(i));
const second = Rx.Observable.of(11).delay(500).do(i => console.log(i));
const third = Rx.Observable.of(111).do(i => console.log(i));

first
  .flatMap(() => second)
  .flatMap(() => third)
  .subscribe(()=> console.log('finished'));

结果将是:

"1"
"11"
"111"
"finished"