我们正在使用Retrofit构建一个与服务器通信的应用程序,如果出现网络错误,则应显示一个对话框(相当于一个toast),并在用户单击该对话框后重做该请求。
问题是我们想要处理它全局,而不是围绕每个请求编写重复的代码。使用this question中带有可观察视图事件的a.bertucci所描述的onErrorResumeNext()
看起来很完美但不幸的是它在Retrofit.Idle
线程中运行并且无法启动任何UI元素。有可能解决这个问题吗?
一个失败的例子:
public static <T> Func1<Throwable, ? extends Observable<? extends T>> retryOnNetworkError(final Activity activity, final Observable<T> toBeResumed) {
return new Func1<Throwable, Observable<? extends T>>() {
@Override
public Observable<? extends T> call(Throwable throwable) {
if (throwable instanceof RetrofitError &&
RetrofitUtils.isNetworkError((RetrofitError) throwable)) {
return dialog(activity, R.string.dialog_title_network_error, R.string.dialog_msg_network_error)
.filter(ok -> ok)
.flatMap(ok -> toBeResumed);
}
return Observable.error(throwable);
}
};
}
public static Observable<Boolean> dialog(Context context, int title, int message) {
return Observable.create((Subscriber<? super Boolean> subscriber) -> {
final AlertDialog ad = new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
subscriber.onNext(true);
subscriber.onCompleted();
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
subscriber.onNext(false);
subscriber.onCompleted();
})
.create();
// cleaning up
subscriber.add(Subscriptions.create(ad::dismiss));
ad.show();
});
}
答案 0 :(得分:0)
您无法在Observable中显示UI元素。你需要在UI线程上运行它。我有同样的错误,这是我的解决方案:
Activity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog(Activity, "Information : ", R.drawable.box_info, "Empty !").show;
}
});
public Observable<Boolean> add(Objet myObj) {
return Observable.create(new Observable.OnSubscribeFunc<Boolean>() {
@Override
public Subscription onSubscribe(Observer<? super Boolean> observer) {
System.out.println("In Observable ! ");
try {
observer.onNext(MyObjet.callmethod()); //callMethod retunr a boolean
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
MyAlertDialog(mActivity, "My Title : ", R.drawable.box_info, "My Text");
}
});
observer.onCompleted();
} catch (Exception e) {
observer.onError(e);
e.printStackTrace();
}
return Subscriptions.empty();
}
}).subscribeOn(Schedulers.threadPoolForIO());
}
使用此方法,您可以在线程中调用对话框。