RXJava2: correct pattern to chain retrofit requests

后端 未结 2 1079
灰色年华
灰色年华 2021-01-04 12:41

I am relatively new to RXJava in general (really only started using it with RXJava2), and most documentation I can find tends to be RXJava1; I can usually translate between

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 13:18

    I would suggest using flat map (And retrolambda if that is an option). Also you do not need to keep the return value (e.g Single first) if you are not doing anything with it.

    retrofitService.getSomething()
        .flatMap(firstResponse -> retrofitService.getSecondResponse(firstResponse.id)
        .subscribeWith(new DisposableSingleObserver() {
             @Override
             public void onSuccess(final SecondResponse secondResponse) {
                // we're done with both!
             }
    
             @Override
              public void onError(final Throwable error) {
                 // a request request Failed, 
              }                        
       });
    

    This article helped me think through styles in how I structure RxJava in general. You want your chain to be a list of high level actions if possible so it can be read as a sequence of actions/transformations.

    EDIT Without lambdas you can just use a Func1 for your flatMap. Does the same thing just a lot more boiler-plate code.

    retrofitService.getSomething()
        .flatMap(new Func1 {
            public void Observable call(FirstResponse firstResponse) {
                return retrofitService.getSecondResponse(firstResponse.id)
            }
        })
        .subscribeWith(new DisposableSingleObserver() {
             @Override
             public void onSuccess(final SecondResponse secondResponse) {
                // we're done with both!
             }
    
             @Override
              public void onError(final Throwable error) {
                 // a request request Failed, 
              }                        
       }); 
    

提交回复
热议问题