【问题标题】:LiveDataReactiveStreams: How to handle errors while using fromPublisher()LiveDataReactiveStreams:如何在使用 fromPublisher() 时处理错误
【发布时间】:2020-07-07 17:23:10
【问题描述】:

我正在尝试使用 Reactive Streams 将 “Flowable” 转换为 “LiveData”。查阅了一堆文章,但我仍然没有掌握处理错误状态的概念。目前,我正处于学习 RxJava 的初级阶段。如果有人能详细解释我应该如何处理这个问题,那将非常有帮助。

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;
    }}

错误堆栈跟踪:

    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

【问题讨论】:

    标签: android rx-java2 android-livedata reactive-streams


    【解决方案1】:

    很简单:LiveData 不处理错误。你来处理它们。

    实时数据比反应式可观察数据要简单得多。实时数据负责交付 100% 完整的对象。就是这样。

    如果您查看LiveDataReactiveStreams.fromPublisher (here) 的文档,您会看到明确表示实时数据不处理错误:

    请注意,LiveData 不处理错误,它希望错误被视为所保存数据中的状态。如果发布者发出错误,错误将传播到主线程,应用程序将崩溃。

    为避免崩溃使用onErrorReturn:

     LiveData<MovieJsonData> _source = LiveDataReactiveStreams.fromPublisher(
                _movieApi.getTrendingMovies(API_KEY)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .onErrorReturn(error -> EmptyMovieJsonData())
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-06
      • 2016-02-18
      • 2023-03-02
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      相关资源
      最近更新 更多