0
votes

I'm new to RxJava. I am currently modifying an existing synchronous flow and making asynchronous using returned observables for the existing methods.

In one of the flows I make a remote call to receive an item from the DB. since the call to the database is asynchronous I am given back an observable. however, the item might not exist in the database in which case the value will be NULL.

if the value is NULL I need to go and make additional asynchronous calls to various other remote services and eventually return the observable response.

what I don't understand is how to implement such a flow with RxJava. here is a sample pseudo code:

void searchSomethingAsych(String key) {

    Observable<SearchResult> result = doTheSearch(key);
}

Observable<SearchResult> doTheSearch(String key) {

    Observable<SearchResult> resultFromDb = checkIfExistsInDb(key);

    // THIS IS WHERE I AM NOT SURE HOW TO DO THIS
    resultFromDb.subscribe((result)- > {
        if(result == null){
            // .. go get this from somewhere else
            Observable<SearchResult> resultFromSomewhere = getSearchResultFromSomewhereElse(key);

            // how do I return the 'resultFromSomewhere' ????
        }
    });

}
1

1 Answers

2
votes

You can use Observable.flatmap(func), where func is function returning another Observable:

resultFromDb.flatMap((result) -> {
    if(result == null){
        return getSearchResultFromSomewhereElse(key);
    } else {
      return Observable.just(result)
});