Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 659
Mathbl Avatar asked Sep 27 '22 02:09

Mathbl


1 Answers

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.

like image 160
Mathbl Avatar answered Sep 28 '22 15:09

Mathbl