繁体   English   中英

RxJS:如何在嵌套订阅调用之间组织订阅

[英]RxJS : how to organize subscription betwen nested subscribing calls

在我的 Angular 应用程序中,我进行了以下处理:

  • 从主题调用 (SubjectOne) 启动订阅者的 OnInit

  • 当有来自 SubjectOne 的新数据时,

    如果某些条件得到验证; 我重新使用这些数据来启动第二个调用,这是来自服务调用的 http 调用。

这是我的代码

我的组件.ts :

  ngOnInit() {
    this.getFirstTreatment();
  }

  getFirstTreatment() {
    this.subscriptionOne = this.myService.subjectOne.subscribe((data) => {
      this.myValue = data['myValue'];
      this.getSecondTreatment(data['myValue'])
    })
  }

  getSecondTreatment(thatValue) {
    if(thatValue >= 100){
     this.subscriptionTwo = this.myService.sendToBackend(thatValue).subscribe((response)=>{}
    }
  }

我的服务.ts

sendToBackend(thatValue){
    let newValue = someFormatingnMethod(thatValue)
    return this.httpClient.post(url , newValue );
}

我的目的是我如何动态关闭subscribtionTwo以便每次从主题获取新数据后它不会被调用 n 次。

注意:即使在销毁组件之前,mySubject 也可以注意到一些新数据

我尝试使用switchMap ,但它似乎无法正常工作

建议?

  • 你从一个 observable 开始
  • 该 observable 在发出值后保持打开状态,因此我们需要取消订阅
  • 然后,您想根据第一个 observable 的结果有条件地运行第二个 observable

我会采取这种方法:

  • 像现在一样设置你的第一个 observable
  • 使用takeUntil在销毁时取消订阅
  • 使用filter仅根据条件继续
  • 使用switchMap运行第二个 observable
  • 第二个 observable 是一个HttpClient请求,它自己完成,所以我们不需要取消订阅
private destroyed$ = new Subject();

ngOnInit() {
  getFirstTreatment();
}

ngOnDestroy() {
  this.destroyed$.next();
  this.destroyed$.complete();
}

getFirstTreatment() {
  this.myService.subjectOne.pipe(
    takeUntil(this.destroyed$),
    tap(data => this.myValue = data['myValue']),    
    filter(data => data['myValue'] >= 100),
    switchMap(data => this.getSecondTreatment(data['myValue']))
  ).subscribe(data => {
    console.log(data); // the output of the second observable    
  });
}

getSecondTreatment(myValue): Observable<any> {
  return this.getSecondTreatment(myValue);
}

暂无
暂无

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

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