I am currently trying to implement the new ViewModels in the architecture components with an API request from retrofit and Okhttp, everything is working but I can't figure out how to pass an error response from retrofit to LiveDataReactiveStreams.fromPublisher and then upstream to the observer in the fragment. This is what I have so far:
public class ShowListViewModel extends AndroidViewModel {
private final ClientAdapter clientAdapter;
private LiveData<List<Show>> shows;
public ShowListViewModel(Application application) {
super(application);
clientAdapter = new ClientAdapter(getApplication().getApplicationContext());
loadShows();
}
public LiveData<List<Show>> getShows() {
if (shows == null) {
shows = new MutableLiveData<>();
}
return shows;
}
void loadShows() {
shows = LiveDataReactiveStreams.fromPublisher(Observable.fromIterable(ShowsUtil.loadsIds())
.subscribeOn(Schedulers.io())
.flatMap(clientAdapter::getShowWithNextEpisode)
.observeOn(Schedulers.computation())
.toSortedList(new ShowsUtil.ShowComparator())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable());
}
And in the fragment I setup the viewModel with the following in OnCreate:
ShowListViewModel model = ViewModelProviders.of(this).get(ShowListViewModel.class);
model.getShows().observe(this, shows -> {
if (shows == null || shows.isEmpty()) {
//This is where we may have empty list etc....
} else {
//process results from shows list here
}
});
Everything works as expected but currently if we are offline then retrofit is throwing a runtimeException and crashing. I think the problem lies here:
LiveDataReactiveStreams.fromPublisher(Observable.fromIterable(ShowsUtil.loadsIds())
.subscribeOn(Schedulers.io())
.flatMap(clientAdapter::getShowWithNextEpisode)
.observeOn(Schedulers.computation())
.toSortedList(new ShowsUtil.ShowComparator())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable());
}
Normally we would use rxjava2 subscribe and catch the error from retrofit there, but when using LiveDataReactiveStreams.fromPublisher it subscribes to the flowable for us. So how do we pass this error into here:
model.getShows().observe(this, shows -> { //process error in fragment});