我的软件有几个案例,其中我有一组可观察值,我需要按顺序执行它们。只有在上一个订阅完成后才会进行下一个订阅。
所以我正在使用 concat
运算符。它工作得很好,但是每次 Observables
之一完成时都会触发它的订阅,我只需要在一切完成后触发它。
concat(
of(1, 2, 3).pipe(delay(3000)),
// after 3s, the first observable will complete and subsquent observable subscribed with values emitted
of(4, 5, 6).pipe(delay(3000)),
)
// log: 1,2,3,4,5,6
.subscribe((v) => {
// Needs to be triggered once after everything is complete
console.log(v);
});
我需要一种方法来管理这个可观察对象,以便订阅在一切完成后仅被触发一次,订阅的值在这种情况下并不重要,因此可以省略。
如果可能,可以在订阅上下文中以数组的形式提供这些值。
最佳答案
用 toArray
收集数组中的值.
import { toArray } from 'rxjs/operators';
concat(
of(1, 2, 3).pipe(delay(3000)),
of(4, 5, 6).pipe(delay(3000)),
).pipe(
toArray()
).subscribe(v => console.log(v)); // log: [1,2,3,4,5,6]
或者,如果您不需要响应,请像@Willem 的解决方案中那样使用 complete
回调。
关于javascript - Concat Array of Observables 并有一个单一的订阅输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150131/