I'm in the process of migrating my Android app to Retrofit 2.0. I had a custom ErrorHandler extending RetrofitError
so I could react to different Http errors.
Now I understand I must create a custom CallAdapterFactory
. I used the sample ErrorHandlingCallAdapter
provided here.
My resulting CallAdapter
is pretty much the same code, but if needed I could also post my code.
What's happening is that when I use this CallAdapterFactory
, callbacks are not happening on the MainThread. I get android.view.ViewRootImpl$CalledFromWrongThreadException
when trying to update the UI (which I always need to). I also don't want to always wrap my code with runOnUIThread in my callbacks.
I don't know if this helps, but when I log Thread.currentThread().getName()
in my callbacks, it returns OkHttp.
I ended up passing an executor to my CallAdapter.Factory:
public static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(@NonNull Runnable r) {
handler.post(r);
}
}
...
.addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory(new MainThreadExecutor()))
and wrapping the callback in:
callbackExecutor.execute(new Runnable() {
@Override
public void run() {
}
});
I inspired myself from this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With