Android:Retrofit回调成功和失败异步执行?

时间:2014-10-21 21:29:00

标签: android multithreading asynchronous thread-sleep retrofit

今天我只是在我们自己的Jake Wharton做一些关于Retrofit的研究,所以我做了类似的事情

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();}
}}); 

我预计会有ANR,但流程正在顺利进行,Jake Wharton在这篇文章中提到过 Does Retrofit make network calls on main thread? “正如它在答案中所述,如果你使用第二种模式(最后一个参数作为回调),请求是异步完成的,但是在主线程上调用了回调。默认情况下,Retrofit使用线程池来处理这些请求。” p>

回调是在主线程上执行的,这里发生了什么,有什么见解吗?为什么Thread.sleep()不会导致ANR ......?我很困惑......

1 个答案:

答案 0 :(得分:2)

默认情况下,Callback Executor使用的Android平台为MainThreadExecutor

确保在通过执行此类操作创建RestAdapter时不会覆盖默认实现

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

如果您通过设置自己来覆盖默认Callback Executor,那么您将无法获得默认行为。