Sree
Sree

Reputation: 2787

How do you chain multiple observables?

Let's say I want to show some user data which is on the server. I would search the server, cache it, and then present it to the user. So my intial RxJava code would look something like this:

 ApiClient.getUser(userId), //An Observable that will spit out a UserResponse
    .subscribeOn(Schedulers.io()) //for the API observable (Do i need this?)
    .flatMap(new Func1<UserResponse, Observable<DatabasePutResult>>() {
          @Override
           public Observable<DatabasePutResult> call(UserResponse response) {
                return Database.cacheUser(response);
             }
          })
    .subscribeOn(Schedulers.io()) //for the database observable
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(//handle DatabasePutResult object in onNext());

Now, I have two questions.

  1. Is that the right way to chain the two Observables? If not, how should I be doing it?
  2. If I wanted to handle the onError for the Api Observable, would I be able to that somehow while maintaining the chain? If not, what is the best way to do this? Do I really need to separate out the chain into two sets of RxJava calls?

Upvotes: 1

Views: 257

Answers (1)

Dmitry  Ok
Dmitry Ok

Reputation: 145

  1. You don't need this:

.subscribeOn(Schedulers.io()) //for the API observable (Do i need this?)

If you are interesting you may check current thread's id by this code:

Thread.currentThread().getId();
Everything else was fine.

  1. You should look at this: Error-Handling-Operators. In this case, I would advise to take a closer look at onErrorResumeNext( )

Hope it will be helpful.

Upvotes: 1

Related Questions