Rxjs 订阅forkJoin中的每个观察值
我希望使用forkJoin一致地调度多个观测值,但希望单独订阅每个观测值,如下所示Rxjs 订阅forkJoin中的每个观察值,rxjs,rxjs-observables,Rxjs,Rxjs Observables,我希望使用forkJoin一致地调度多个观测值,但希望单独订阅每个观测值,如下所示 const ox = http.get('x'); const oy = http.get('y'); const all = interval(1000).pipe( switchMap( () => forkJoin(ox, oy) ); ); // component x const sx = ox.subscribe((x) => { showX(x); }); // com
const ox = http.get('x');
const oy = http.get('y');
const all = interval(1000).pipe(
switchMap(
() => forkJoin(ox, oy)
);
);
// component x
const sx = ox.subscribe((x) => { showX(x); });
// component y
const sy = oy.subscribe((y) => { showY(y); });
// Another component
const sAll = all.subscribe(([x, y]) => { doStuffThatNeedsBothXY(x, y); });
这样做的最佳方式是什么?我想让
ox
和oy
类型保持可见,而不是在所有中使用管道副作用(tap
)等其他技术。似乎没有必要订阅每个单独的流,也没有必要订阅这两个流
你可以这样做:
sAll = combineLatest(this.toDos$, this.posts$)
.pipe(
tap(([todos, posts]) => {
this.todos = todos;
this.posts = posts;
})
)
.subscribe(() => console.log("subscribe"));
使用combineLatest
自动订阅每个流,并允许您同时访问这两个流
注意:如果您订阅了ox并订阅了ox和另一个流的组合,那么您将订阅该流两次,并第二次发出x的HTTP请求。你可以在我的Stackblitz样本中尝试一下
我这里有一个Stackblitz的例子:
或者用变量查看它:
sAll = combineLatest(ox, oy)
.pipe(
tap(([x, y]) => {
showX(x);
showY(y);
doStuffThatNeedsBothXY(x,y);
})
)
.subscribe(() => console.log("subscribe"));
如果这与您的需求不匹配,您能否更具体地说明需要所有三个订阅的用例