我目前正在尝试使用来自retrofit和Okhttp的API请求在体系结构组件中实现新的ViewModels,一切都正常,但我不知道如何将错误响应从retrofit传递到LiveDataReactiveStreams.fromPublisher,然后上游传递到片段中的观察者。这就是我到目前为止所知道的:
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());
}在片段中,我在OnCreate中使用以下内容设置了viewModel:
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
        }
    });一切都像预期的那样工作,但是现在如果我们离线了,那么retrofit就会抛出一个runtimeException并崩溃。我认为问题出在这里:
LiveDataReactiveStreams.fromPublisher(Observable.fromIterable(ShowsUtil.loadsIds())
            .subscribeOn(Schedulers.io())
            .flatMap(clientAdapter::getShowWithNextEpisode)
            .observeOn(Schedulers.computation())
            .toSortedList(new ShowsUtil.ShowComparator())
            .observeOn(AndroidSchedulers.mainThread())
            .toFlowable());
}通常我们会使用rxjava2订阅并在那里捕获改造的错误,但当使用LiveDataReactiveStreams.fromPublisher时,它会为我们订阅flowable。那么我们如何将这个错误传递到这里:
model.getShows().observe(this, shows -> { //process error in fragment});
https://stackoverflow.com/questions/46304042
复制相似问题