我目前正在尝试使用来自改造和 Okhttp 的 API 请求在架构组件中实现新的 ViewModel,一切正常,但我不知道如何将错误响应从改造传递到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
}
});
一切都按预期工作,但目前如果我们处于离线状态,那么改造会抛出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 subscribe 并捕获来自改造的错误,但是当使用LiveDataReactiveStreams.fromPublisher https://developer.android.com/reference/android/arch/lifecycle/LiveDataReactiveStreams.html它为我们订阅了 flowable。那么我们如何将这个错误传递到这里:
model.getShows().observe(this, shows -> { //process error in fragment});