RxJava doOnError 与 onError

RxJava doOnError vs onError

我正在尝试使用下面的代码

initLocalSettingsIfNeed()
                            .andThen(initGlobalSettingsIfNeed(configuration))
                            .doOnComplete(callback::onSuccess)
                            .doOnError(throwable -> callback.onError(throwable.getLocalizedMessage()))
                            .subscribe();

但我有例外

The exception was not handled due to missing onError handler in the subscribe() method call.

我想我没有正确使用这个方法,我认为可以用 subscribe() 方法中的观察者替换 doOnComplete doOnError,我错了吗?

试试这个

initLocalSettingsIfNeed()
    .andThen(initGlobalSettingsIfNeed(configuration))
    .subscribe({completed->
        callback.onSuccess()
    },{throwable->
        callback.onError(throwable.getLocalizedMessage())
    })

关于你原来的问题,你必须知道 doOnError 不是 onError 的替代品。您在 this blog:

中对此有一个很好而简短的解释

Actually there’s one key difference between them. doOnError() basically only triggers its callback, then passes down the encountered errors to the down stream. So if the whole stream is subscribed without the onError callback in subscribe(), your app will crash by OnErrorNotImplementedException.

The onError callback in subscribe() in the other hand does consume the errors. That means, it will catch the errors, and let you handle them without re-throwing the errors by itself.

关于您在一条评论中提到的警告:

This approach is working, but i have warning 'the result of subscribe not used', as i know this need to be disposed automatically when onError or onComplete is called, is there way to avoid this warning? – Pavel Poley

一个好的方法是你的方法在你的Repositoryreturn一个Observable中,然后你可以在你的ViewModel中订阅它们。然后,在每个 ViewModel class 中,您可以有一个带有 CompositeDisposable 的成员变量,您可以在其中将每个订阅的一次性添加到由您的存储库编辑的 Observables return。最后,您应该覆盖 onCleared 方法来处理存储在 CompositeDisposable.

中的所有一次性用品
public class MyViewModel extends ViewModel {

    private MyRepository myRepository;
    private final CompositeDisposable disposables;

    @Inject
    public MyViewModel(MyRepository myRepository) {
        ...
        this.myRepository = myRepository;
        disposables = new CompositeDisposable();
        ...
    }

    public void callObservableInRepository() {
         disposables.add(myRepository.myObservable()
                              .subscribe(onSuccess -> {...} , onError -> {...}));
    }

    @Override
    protected void onCleared() {
        disposables.clear();
    }

}