繁体   English   中英

Angular 等待所有订阅完成

[英]Angular wait for all subscriptions to complete

在 Angular 中,一个页面对多个操作进行多次 http 调用,比如说按钮点击。 但是当最后一个“完成”按钮被按下时,我想确保所有这些请求都在它进行之前完成。 我尝试将forkJoin与 observables 一起使用,但它本身会触发请求,这不是我想要做的,我希望其他操作来触发请求,并确保在单击“DONE”时完成异步请求。 有了承诺,我只需将承诺推送到数组,然后执行Promise.all(allRequests).then(()=>{})

observables: Observable<any>[];

onBtn1Click(){
   let o1 = this.service.doAction1();
   this.observables.push(o1);
   
   o1.subscribe(resp => {
        //do action1
   });
}

onBtn2Click(){
   let o2 = this.service.doAction2();
   this.observables.push(o2);
   
   o2.subscribe(resp => {
        //do action2
   });
}

onDoneClick(){
   // I would like something like this just that it wouldn't trigger the requests but make sure they are completed. 
   forkJoin(this.observables).subscribe(()=>{
     //Proceed with other things
   });
}

除非有人想出一个优雅的方法,否则应该这样做。

我正在创建一个 object 来为来自 HTTP 请求的每个冷可观察对象保持热可观察对象。 该请求将使用 RxJS finalize运算符向其相应的热可观察对象发出。 然后可以使用forkJointake(1)组合这些热的 observable,以等待源请求完成。

private httpReqs: { [key: string]: ReplaySubject<boolean> } = Object.create(null);

onBtn1Click() {
  this.httpReqs['btn1'] = new ReplaySubject<boolean>(1);
  this.service.doAction1().pipe(
    finalize(() => this.httpReqs['btn1'].next(true))
  ).subscribe(resp => {
    // do action1
  });
}

onBtn2Click() {
  this.httpReqs['btn2'] = new ReplaySubject<boolean>(1);
  this.service.doAction1().pipe(
    finalize(() => this.httpReqs['btn2'].next(true))
  ).subscribe(resp => {
    // do action2
  });
}

onDoneClick(){
  forkJoin(
    Object.values(this.httpReqs).map(repSub =>
      repSub.asObservable().pipe(
        take(1)
      )
    )
  ).subscribe(() => {
    // Proceed with other things
  });
}

使用shareReplay

如果您多播,订阅完整 stream 的任何订阅者都会收到complete通知。 你可以利用它。

各种共享运算符都有一个隐式refCount ,每隔几个 RxJS 版本就会更改其默认值。 shareReplay(n)的当前版本非常直观,但您可能需要在旧版本上设置refCount:false ,甚至使用multicast(new ReplaySubject(1)), refCount()

onBtn1Click(){
  let o1 = this.service.doAction1().pipe(
    shareReplay(1)
  );
  this.observables.push(o1);
   
  o1.subscribe(resp => {
    //do action1
  });
}

这是最小的改变,应该让你的代码按照你想要的方式工作

扫描以统计活动

如果只计算当前活动的操作,则可以完全避免 forkJoin。

count = (() => {
  const cc = new BehaviorSubject<number>(0);
  return {
    start: () => cc.next(1),
    stop: () => cc.next(-1),
    value$: cc.pipe(
      scan((acc, curr) => acc + curr, 0)
    )
  }
})();

onBtn1Click(){
  this.count.start();

  this.service.doAction1().pipe(
    finalize(this.count.stop)
  ).subscribe(resp => {
    //do action1
  });
}

onDoneClick(){
  this.count.value$.pipe(
    first(v => v === 0) // Wait until nothing is currently active
  ).subscribe(() => {
    //Proceed with other things
  });

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM