RxJava doOnError 与 onError

Pav*_*ley 7 android rx-java rx-java2

我尝试使用以下代码

initLocalSettingsIfNeed()
                            .andThen(initGlobalSettingsIfNeed(configuration))
                            .doOnComplete(callback::onSuccess)
                            .doOnError(throwable -> callback.onError(throwable.getLocalizedMessage()))
                            .subscribe();
Run Code Online (Sandbox Code Playgroud)

但我有例外

由于 subscribe() 方法调用中缺少 onError 处理程序,因此未处理异常。

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

dgl*_*ano 7

关于您原来的问题,您必须知道这doOnError不是onError. 你在这个博客中有一个很好的简短的解释:

实际上,它们之间有一个关键区别。doOnError() 基本上只触发它的回调,然后将遇到的错误传递给下游。因此,如果在 subscribe() 中没有 onError 回调的情况下订阅了整个流,您的应用程序将因 OnErrorNotImplementedException 而崩溃。

另一方面, subscribe() 中的 onError 回调确实消耗了错误。这意味着,它将捕获错误,并让您处理它们而无需自行重新抛出错误。

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

这种方法有效,但我有警告“未使用订阅的结果”,因为我知道这需要在调用 onError 或 onComplete 时自动处理,有没有办法避免此警告?– 帕维尔·波利

一个好的方法是你的方法在你的里面Repository返回一个Observable,然后你可以在你的ViewModel. 然后,在每个ViewModel类中,您都可以有一个成员变量CompositeDisposable,您可以在其中将每个订阅的一次性添加到存储库返回的 Observables 中。最后,您应该覆盖该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();
    }

}
Run Code Online (Sandbox Code Playgroud)