Chain two retrofit observables w/ RxJava

前端 未结 2 1935
一向
一向 2020-12-25 12:27

I want to execute 2 network calls one after another. Both network calls return Observable. Second call uses data from successful result of the first call, method in successf

相关标签:
2条回答
  • 2020-12-25 12:58

    Have you looked into flatMap()? If your aversion to it (or zip()) is the need to make an unnecessary class just to hold two objects, android.util.Pair might be an answer. I'm not sure how to get exactly the error handling you're looking for, though.

           API().auth(email, password)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(new Func1<AuthResponse, Observable<List<User>>>() {
              @Override
              public Observable<List<User>> call(AuthResponse authResponse) {
                return API().getUser(authResponse.getAccessToken());
              }
            }, new Func2<AuthResponse, List<User>, Pair<AuthResponse, List<User>>>() {
              @Override
              public Pair<AuthResponse, List<User>> call(AuthResponse authResponse, List<User> users) {
                return new Pair<>(authResponse, users);
              }
            }).subscribe(new Action1<Pair<AuthResponse, List<User>>>() {
              @Override
              public void call(Pair<AuthResponse, List<User>> pair) {
                doSomething(pair.first, pair.second);
              }
            }, new Action1<Throwable>() {
              @Override
              public void call(Throwable throwable) {
                // not sure how to tell which one threw the error
              }
            });
    
    0 讨论(0)
  • 2020-12-25 13:06

    In addition to Anthony R.'s answer, there is a flatMap overload which takes a Func2 and pairs your primary and flattened values for you. In addition, look at the onErrorXXX and onExceptionXXX operators for error manipulation, and chain them with your first and second Observables

    first.onErrorReturn(1)
    .flatMap(v -> service(v).onErrorReturn(2), (a, b) -> a + b);
    
    0 讨论(0)
提交回复
热议问题