Chaining dependent Observables in RxJs

浪子不回头ぞ 提交于 2019-12-08 08:47:29

问题


What is "best practices" for chaining a sequence of HttpClient calls (assume the current call depends on the results of the previous calls)? The following solution is functional but apparently not recommended. Each get returns an Observable. Use of the "pipe" operator preferred in solution (the newer approach in RxJs).

ngOnInit() {
  this.firstService.get().subscribe((first) => {
    this.secondService.get().subscribe(second => {
      this.thirdService.get().subscribe(third => {
        ... possibly more nested calls ...
      })
    })
  })
}

回答1:


Your code is far beyond best practice. Never do subscription inside another.

If your tasks are three seperate tasks/observables which do not depends each other, then consider to use forkJoin (all Observables start at the same time and when the last observable finishes It returns result)

let observable1(param1);
let observable2(param2);
let observable3(param3);

let joinedObservables = forkJoin(observable1, observable2, observable3).subscribe(x => {
  let result1 = x[0];
  let result2 = x[1];
  let result3 = x[2];

  ...
});

If their results depends on each other you can use switchMap, flatMap, mergeMap, exhaustMap (check differences)

let resultObservable =  return this.observable1().pipe(mergeMap((param1) => {
  return this.observable2().pipe(map((param1) => {

    ....        

    return <result>;
  }));
}));

resultObservable.subscribe(x => {
   ...
});



回答2:


If the reason why you need nested calls is to use data from the previous calls, I recommend using the pipe operator with mergeMaps and more pipes/maps to return the next calls in place of the previous.

Should be something similar to (subscribes and unsubscribes omitted):

this.firstService.pipe(
    mergeMap(res =>
        this.secondService.get().pipe(
            map(data => data),
        ),
    ... <more as needed>
);

If they don't need to be nested, it's easier to do this.service.get().toPromise() inside a promiseAll.



来源:https://stackoverflow.com/questions/54281566/chaining-dependent-observables-in-rxjs

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