Joã*_*lva 3 javascript observable rxjs
我的软件中有几个案例,其中我有一组可观察对象,我需要按顺序执行它们。只有在前一个订阅完成后才会进行下一个订阅。
所以我使用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);
});
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来管理这个 observable,这样订阅只会在一切完成后触发一次,在这种情况下订阅的值并不重要,因此可以省略它。
如果可能,可以在订阅上下文中以数组的形式提供这些值。
使用 收集数组中的值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]
Run Code Online (Sandbox Code Playgroud)
或者,如果您不需要响应,请使用complete@Willem 解决方案中的回调。