I am trying to convert a "Flowable" to "LiveData" using Reactive Streams. Looked up a bunch of articles but I still haven't grasped the concept of handling error states. Currently, I am in the beginning phases of learning RxJava. It would be really helpful if someone can provide me with a detailed explanation on how I should handle this problem.
Repository.java
public class Repository {
private static final String API_KEY = "";
private static final String TAG = "Repository class- ";
private MovieService _movieApi;
private MediatorLiveData<MovieJsonData> _movieList;
private static Repository _repositoryInstance;
public static Repository getInstance(){
if(_repositoryInstance == null){
return new Repository();
}
return _repositoryInstance;
}
private Repository(){
_movieApi = MovieClient.getTrendingMovieClient().create(MovieService.class);
_movieList = new MediatorLiveData<>();
}
public MediatorLiveData<MovieJsonData> fetchData(){
LiveData<MovieJsonData> _source = LiveDataReactiveStreams.fromPublisher(
_movieApi.getTrendingMovies(API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(error -> Log.d(TAG, "fetchData: " + error.getMessage()))
);
_movieList.addSource(_source, new Observer<MovieJsonData>() {
@Override
public void onChanged(MovieJsonData movieJsonData) {
_movieList.setValue(movieJsonData);
}
});
return _movieList;
}}
Error stack trace:
D/Repository class-: fetchData: timeout
W/System.err:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to
the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to
begin with.
Caused by: java.lang.RuntimeException: LiveData does not handle errors. Errors from publishers should
be handled upstream and propagated as state
It's simple: LiveData does not handle errors. You handle them.
Live data is a lot simpler than reactive observables. Live data is responsible for delivering 100% intact objects. That is it.
If you take a look at the documentation of LiveDataReactiveStreams.fromPublisher
(here) you will see that it is explicitly said that live data does not handle errors:
Note that LiveData does NOT handle errors and it expects that errors are treated as states in the data that's held. In case of an error being emitted by the publisher, an error will be propagated to the main thread and the app will crash.
To avoid crashing use onErrorReturn
:
LiveData<MovieJsonData> _source = LiveDataReactiveStreams.fromPublisher(
_movieApi.getTrendingMovies(API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(error -> EmptyMovieJsonData())
);