How to finalize nested Observables?

一笑奈何 提交于 2019-12-20 06:26:26

问题


Please, take a look at the following try for better understanding:

this.loading = true;
obs.pipe(
   finalize(() => this.loading = false) //If set to false here and the person has children then there will be another request and the requests are not over yet
).subscribe(person => {
    if(person && person.children){
       obs2.pipe(
          finalize(() => this.loading = false) //If only set to false here and the person has no children then the false property will never actually be set to false
       ).subscribe(children => {
          //Do stuff with response
       })
    }
})

My goal is to set the loading property to false just at the end of the request or requests if that is the case.

I hope to have explained my problem well. Thanks in advance.


回答1:


You should use the switchMap operator to combine the two observables into one:

this.loading = true;
loadParent().pipe(
  switchMap(parent => {
    if (person.children) {
      return loadChildrenOf(parent).pipe(
        map(children => ({ parent, children })
      )
    } else {
      return of({parent, children: [] })
    }
  }),
  finalize(() => this.loading = false)
).subscribe(({ parent, children }) => {
  // Do stuff with the parent and its children
});


来源:https://stackoverflow.com/questions/57638183/how-to-finalize-nested-observables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!