Search code examples
javaandroidrx-javarx-java2

Observable.concat with Exception


I have 2 data sources: DB and server. When I start the application, I call the method from the repository (MyRepository):

public Observable<List<MyObj>> fetchMyObjs() {
    Observable<List<MyObj>> localData = mLocalDataSource.fetchMyObjs();
    Observable<List<MyObj>> remoteData = mRemoteDataSource.fetchMyObjs();
    return Observable.concat(localData, remoteData);
}

I subscribe to it as follows:

mMyRepository.fetchMyObjs()         
            .compose(applySchedulers())
            .subscribe(
                    myObjs -> {
                        //do somthing
                    },
                    throwable ->  {
                        //handle error
                    }
            );

I expect that the data from the database will be loaded faster, and when the download of data from the network is completed, I will simply update the data in Activity.

When the Internet is connected, everything works well. But when we open the application without connecting to the network, then mRemoteDataSource.fetchMyObjs(); throws UnknownHostException and on this all Observable ends (the subscriber for localData does not work (although logs tell that the data from the database was taken)). And when I try to call the fetchMyObjs() method again from the MyRepository class (via SwipeRefresh), the subscriber to localData is triggered.

How can I get rid of the fact that when the network is off, when the application starts, does the subscriber work for localData?


Solution

  • Try some of error handling operators:

    https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators

    I'd guess onErrorResumeNext( ) will be fine but you have to test it by yourself. Maybe something like this would work for you:

    Observable<List<MyObj>> remoteData = mRemoteDataSource.fetchMyObjs()
          .onErrorResumeNext()
    

    Addidtionally I am not in position to judge if your idea is right or not but maybe it's worth to think about rebuilding this flow. It is not the right thing to ignore errors - that's for sure ;)