How to properly handle onError inside RxJava (Android)?

后端 未结 3 1440
南笙
南笙 2021-01-01 09:56

I\'m getting a list of installed apps on the device. It\'s a costly operation, so I\'m using Rx for that:

    Observable observable = Observable         


        
3条回答
  •  无人及你
    2021-01-01 10:16

    Here is the newbie response (because I am new in javarx and finally fix this issue) :

    Here is your implementation :

        Observable.create(new Observable.OnSubscribe() {
                    @Override
                    public void call(Subscriber subscriber) {
                        subscriber.onError(new Exception("TADA !"));
                    }
                })
                .doOnNext(actionNext)
                .doOnError(actionError)
                .doOnCompleted(actionCompleted)
                .subscribe();
    

    In this previous implementation, when I subscribe I trigger the error flow ... and I get an application crash.

    The problem is that you HAVE TO manage the error from the subscribe() call. The "doOnError(...)" is just a kind of helper that clone the error and give you a new place to do some action after an error. But it doesn't Handle the error.

    So you have to change your code with that :

        Observable.create(new Observable.OnSubscribe() {
                    @Override
                    public void call(Subscriber subscriber) {
                        subscriber.onError(new Exception("TADA !"));
                    }
                })
                .subscribe(actionNext, actionError, actionCompleted);
    

    Not sure about the real explanation, but this is how I fix it. Hope it will help.

提交回复
热议问题