RXJava2: correct pattern to chain retrofit requests

后端 未结 2 1057
灰色年华
灰色年华 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<FirstResponse> first) if you are not doing anything with it.

    retrofitService.getSomething()
        .flatMap(firstResponse -> retrofitService.getSecondResponse(firstResponse.id)
        .subscribeWith(new DisposableSingleObserver<SecondResponse>() {
             @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<FirstResponse, Observable<SecondResponse> {
            public void Observable<SecondResponse> call(FirstResponse firstResponse) {
                return retrofitService.getSecondResponse(firstResponse.id)
            }
        })
        .subscribeWith(new DisposableSingleObserver<SecondResponse>() {
             @Override
             public void onSuccess(final SecondResponse secondResponse) {
                // we're done with both!
             }
    
             @Override
              public void onError(final Throwable error) {
                 // a request request Failed, 
              }                        
       }); 
    
    0 讨论(0)
  • 2021-01-04 13:26

    Does this not work for you?

    retrofitService
    .getSomething()
    .flatMap(firstResponse -> retrofitService.getSecondResponse(firstResponse.id))
    .doOnNext(secondResponse -> {/* both requests succeeded */})
    /* do more stuff with the response, or just subscribe */
    
    0 讨论(0)
提交回复
热议问题