1

Today I was just doing some research on Retrofit by our very own Jake Wharton, so I did something like this

RetroClass.getClient().getSomeData(param, new Callback<Model>(){

@Override 
public void failure(...){/*blah*/}

@Override
public void success(Model response, Response notUsed)
{
try
{
  Thread.sleep(10000);
}
catch(Exception e){e.pST();}
}}); 

I expected a ANR, but the flow is executing fine, Jake Wharton mentioned in this post Does Retrofit make network calls on main thread? "As it states in the answer, if you use the second pattern (last argument as a Callback) the request is done asynchronously but the callback is invoked on the main thread. By default Retrofit uses a thread pool for these requests."

that the call back is executed on the main thread, whats happening here, any insights ? Why isnt Thread.sleep() not causing an ANR here...? Im baffled....

Community
  • 1
  • 1
uLYsseus
  • 995
  • 6
  • 16
  • 37

1 Answers1

2

Yes by default for the Android platform the Callback Executor used is MainThreadExecutor.

Make sure you're not overriding the default implementation when creating your RestAdapter by doing something like this

RestAdapter restAdapter = new RestAdapter.Builder()
            .setExecutors(new MyHttpExecuter(), new MyCallbackExecutor()) { // watch out for this
            .build()

If you override the default Callback Executor by setting your own then you won't get the default behaviour.

Miguel
  • 19,793
  • 8
  • 56
  • 46
  • and its almost like creating a new thread right ? except that you are using an Executor..instead of explicitly calling new Thread(new(ThreadRunnable())) and starting it ? – uLYsseus Oct 21 '14 at 22:40
  • Actually my answer doesn't seem to be the solution to your question. In the case where you DON'T override the default callback then you'd be using the MainThreadScheduler which means that any blocking done from within a callback `onSuccess` or `onFailure` will block the UI. Even if you don't actually get an ANR you should test to see you'll probably notice the UI is blocking while your callback executes. You can even put a breakpoint in your `onSuccess` callback and look at the thread in which it's being executed on using your IDE. – Miguel Oct 21 '14 at 23:05
  • And yes! The Executer interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html – Miguel Oct 21 '14 at 23:26