RxJava: how to compose multiple Observables with dependencies and collect all results at the end?

后端 未结 3 1468
终归单人心
终归单人心 2021-02-07 03:08

I\'m learning RxJava and, as my first experiment, trying to rewrite the code in the first run() method in this code (cited on Netflix\'s blog as a problem RxJava ca

3条回答
  •  甜味超标
    2021-02-07 03:39

    I think what you are looking for is switchmap. We ran into a similar issue where we have a session service that handles getting a new session from an api, and we need that session before we can get more data. We can add to the session observable that returns the sessionToken for use in our data call.

    getSession returns an observable;

    public getSession(): Observable{
      if (this.sessionToken)
        return Observable.of(this.sessionToken);
      else if(this.sessionObservable)
        return this.sessionObservable;
      else {
        // simulate http call 
        this.sessionObservable = Observable.of(this.sessonTokenResponse)
        .map(res => {
          this.sessionObservable = null;
          return res.headers["X-Session-Token"];
        })
        .delay(500)
        .share();
        return this.sessionObservable;
      }
    }
    

    and getData takes that observable and appends to it.

    public getData() {
      if (this.dataObservable)
        return this.dataObservable;
      else {
        this.dataObservable = this.sessionService.getSession()
          .switchMap((sessionToken:string, index:number) =>{
            //simulate data http call that needed sessionToken
              return Observable.of(this.dataResponse)
              .map(res => {
                this.dataObservable = null;
                return res.body;
              })
              .delay(1200)
            })
            .map ( data => {
              return data;
            })
            .catch(err => {
              console.log("err in data service", err);
             // return err;
            })
            .share();
        return this.dataObservable;
      }
    }
    

    You will still need a flatmap to combine the not dependent observables.

    Plunkr: http://plnkr.co/edit/hiA1jP?p=info

    Where I got the idea to use switch map: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

提交回复
热议问题