RxJs Observables nested subscriptions?

前端 未结 3 766
清歌不尽
清歌不尽 2020-11-29 06:22

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.returnsObserv         


        
3条回答
  •  清酒与你
    2020-11-29 07:07

    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]);
      });
    

提交回复
热议问题