Вы можете использовать combineLatest
для выдачи последнего значения из каждого наблюдаемого источника. Он не будет излучаться до тех пор, пока каждый наблюдаемый источник не издаст хотя бы один раз, поэтому вы можете использовать startWith
для предоставления начального значения:
combineLatest(
this.myService.api1().pipe(startWith(null)),
this.myService.api2().pipe(startWith(null)),
this.myService.api3().pipe(startWith(null)),
this.myService.api4().pipe(startWith(null)),
this.myService.api5().pipe(startWith(null))
)
.subscribe(
([r1,r2,r3,r4,r5]) => { ... do something })
Начальный вывод будет [null, null, null, null, null]
. Когда каждое наблюдаемое излучает, оно заменит соответствующее значение null
в массиве.
Если вы хотите игнорировать начальное излучение, вы можете использовать skip(1)
.
const sourceOne = of('Hello').pipe(delay(1000));
const sourceTwo = of('World!').pipe(delay(2000));
const sourceThree = of('Goodbye').pipe(delay(3000));
const sourceFour = of('World!').pipe(delay(4000));
//wait until all observables have emitted a value then emit all as an array
const example = combineLatest(
sourceOne.pipe(startWith(null)),
sourceTwo.pipe(startWith(null)),
sourceThree.pipe(startWith(null)),
sourceFour.pipe(startWith(null))
)
.pipe(skip(1));
//output:
//["Hello", null, null, null]
//["Hello", "World!", null null]
//["Hello", "World!", "Goodbye", null]
//["Hello", "World!", "Goodbye", "World!"]
//Complete
const subscribe = example.subscribe(val => console.log(val), null, () => console.log('Complete'));
И вот StackBlitz , чтобы попробовать его.