Mathbl Mathbl - 1 year ago 172
Android Question

Retrofit 2.0 - Custom CallAdapterFactory - Callbacks not happening on MainThread

I'm in the process of migrating my Android app to Retrofit 2.0. I had a custom ErrorHandler extending

so I could react to different Http errors.

Now I understand I must create a custom
. I used the sample
provided here.

My resulting
is pretty much the same code, but if needed I could also post my code.

What's happening is that when I use this
, callbacks are not happening on the MainThread. I get
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
in my callbacks, it returns OkHttp.

Answer Source

I ended up passing an executor to my CallAdapter.Factory:

public static class MainThreadExecutor implements Executor {
    private final Handler handler = new Handler(Looper.getMainLooper());

    public void execute(@NonNull Runnable r) {;


.addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory(new MainThreadExecutor()))

and wrapping the callback in:

callbackExecutor.execute(new Runnable() {
    public void run() {

I inspired myself from this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download