Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 Callback onResponse on background thread

This has probably been asked before but didn't seem to have a viable answer. We are using Retrofit 2.1.0 async callback which carries out the request on the background thread. However, when the response is received onResponse it is sent back on the application's UI thread regardless of me placing the callback within a new thread forcing it to not utilize the UI.

As we don't want to block the main UI thread for any reason, is it possible for the response to be returned in the background?

If the above is not possible, is it recommended that a separate thread is kicked off from the response in order to avoid UI thread blocking?

Any help would be much appreciated. Thanks!

like image 518
Zishan Neno Avatar asked Dec 28 '16 06:12

Zishan Neno


People also ask

Does retrofit work on background thread?

Retrofit is a third-party library by Square for communicating with REST APIs over HTTP. Similarly to AsyncTasks , work is done in a background thread, and upon completion it returns the result to the main UI thread.

What is callback in retrofit?

Interface Callback<T>Communicates responses from a server or offline requests. One and only one method will be invoked in response to a given request. Callback methods are executed using the Retrofit callback executor.

What thread does retrofit use?

2.1. In retrofit, synchronous methods are executed in the main thread. This means that the UI is blocked during the synchronous request execution and no user interaction is possible in this period. In the above example, we have used the ServiceGenerator class.


1 Answers

You can specify a specific executor for the callbacks to run on when building your Retrofit instance. Here is an example that uses a SingleThreadExecutor for callbacks.

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(/* your url */)
        .callbackExecutor(Executors.newSingleThreadExecutor())
        // other builder options...
        .build();
like image 58
iagreen Avatar answered Sep 17 '22 14:09

iagreen