RxJs Observables nested subscriptions?

六月ゝ 毕业季﹏ 提交于 2019-12-17 06:45:14

问题


Whats the way to simplify something like the following code example? I can't find the right operator.. could anyone give a short example?

this.returnsObservable1(...)
  .subscribe(

    success => {

      this.returnsObservable2(...)
        .subscribe(

          success => {

            this.returnsObservable3(...)
              .subscribe(

                success => {
                   ...
                },

回答1:


As mentioned in comments, you are looking for the flatMap operator.

You can find more details in previous answers :

  • How to do the chain sequence in rxjs
  • Why do we need to use flatMap?

Your example would read as :

this.returnsObservable1(...)
  .flatMap(success => this.returnsObservable2(...))
  .flatMap(success => this.returnsObservable3(...))
  .subscribe(success => {(...)}); 



回答2:


Previously answered for RxJS 5, I ended up on this page whilst using 6.

In the case you're on 6 as well (and I think you should be by now) you can use flatmap as an operator within pipe.

Modified the example code of @user3743222:

this.returnsObservable1(...)
  .pipe(
    flatMap(success => this.returnsObservable2(...)),
    flatMap(success => this.returnsObservable3(...))
  )
  .subscribe(success => {(...)}); 



回答3:


The switchMap operator can also be useful. Some examples which describe the usefulness of switchMap compared to nested subscriptions can be found here:

  1. situation with nested subscriptions

This codepen gives a demo: https://codepen.io/anon/pen/zdXBvP?editors=1111

Rx.Observable
  .interval(5000)
  .subscribe((val) => {
    console.log("outer:", val);
    Rx.Observable
      .interval(1000)
      .subscribe((ival) => {
        console.log("inner:", val, ival); 
      });
  });
  1. situation with switchMap

This codepen gives a demo: https://codepen.io/anon/pen/xLeOZW?editors=1111

Rx.Observable
  .interval(5000)
  .switchMap((val) => {
    console.log("outer:", val);
    return Rx.Observable.interval(1000).map((ival) => [val, ival]);
  })
  .subscribe((val) => {
    console.log("inner:", val[0], val[1]);
  });


来源:https://stackoverflow.com/questions/42888604/rxjs-observables-nested-subscriptions

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