Ar.Len
Ar.Len

Reputation: 3

How can I compare results from Observables and return one of them

I have method to return object of Place, but first i have to check if Place object exist in database then return him or otherwise fetch Place object from rest service. How the easiest way I can check it out ?

public Observable<Place> getPlace(final String id) {

    // Both method from repository and rest are: Observable<Place> getPlace(String id);

    // if placeDatabaseRepository.getPlace(id) != null then:
    return placeDatabaseRepository.getPlace(id);
    // else Place == NULL then:
    return placeRest.getPlace(id);
}

Upvotes: 0

Views: 83

Answers (1)

npace
npace

Reputation: 4258

Dan Lew wrote an excellent article about this very problem.

The gist of it is that you use two Observable<Place> instances - one that returns the result from the database if it's not null, another that returns the result from the REST call. You chain them together with the concat() operator and only take the first emitted item with the first() operator, kind of like so:

Observable<Place> dbSource = Observable
    .just(placeDatabaseRepository.getPlace(id))
    .filter(place -> place != null);
Observable<Place> restSource = Observable
    .just(placeRest.getPlace(id));

return Observable
    .concat(dbSource, restSource)
    .first();

Upvotes: 1

Related Questions