Android 应用断网后,使用OKHTTP+Retrofit+RxJava进行网络请求,应用闪退
2021-12-09 17:17:53.493 1427-1427/com.xxx.android W/System.err: io.reactivex.exceptions.OnErrorNotImplementedException: Unable to resolve host "xxx-api.xxx.com": No address associated with hostname
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.checkTerminated(ObservableObserveOn.java:276)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
2021-12-09 17:17:53.494 1427-1427/com.xxx.android W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2021-12-09 17:17:53.901 1427-1427/com.xxx.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxx.android, PID: 142
2021-12-09 17:17:53.940 1427-1427/com.xxx.android I/Process: Sending signal. PID: 1427 SIG: 9
问题原因: 网络请求失败的情况下Observable有一个异常需要显示处理,也可以通过实现另一个“Consumer<Throwable>” 来得到。
ModelService.requestXXX(x)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseModel>() {
@Override
public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
Log.i("PSF", "XXX-Observable-onSubscribe");
}
@Override
public void onNext(@io.reactivex.annotations.NonNull ResponseModel model) {
Log.i("PSF", "XXX-Observable-onNext");
xxxxxx(model);
}
@Override
public void onError(@io.reactivex.annotations.NonNull Throwable e) {
Log.i("PSF", "XXX-Observable-onError");
}
@Override
public void onComplete() {
Log.i("PSF", "XXX-Observable-onComplete");
}
});
在断网情况下此断代码会抛出异常,修改如下:
Disposable dis = ModelService.requestXXX()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ResponseModel>() {
@Override
public void accept(ResponseModel model) throws Exception {
Log.i("PSF", "XXX-Observable-accept");
xxxxxx(model);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.i("PSF", "XXX-Observable-onError" + throwable.toString());
}
});
|