note answer below is based on Retrofit 1.6.1 - will update for newest version. Retrofit 1.9.0 does not allow you to set the HttpExecutor
via the RestAdapter.Builder
any longer
The accepted answer is a step in the right direction but it makes me feel uncomfortable. In practise you would either need to set the AsyncTask.THREAD_POOL_EXECUTOR
for live & tests builds OR test builds only.
Setting for both would mean all your network IO pooling will depend on the aysnc queue implementation, which became serial by default for apps with target versions ICS+
Setting for tests only would mean that your test build is different from your live build, which imho is not a great place to start testing from. Also you may encounter test problems on older devices due to async pool changes.
It is rightly mentioned above that Espresso
hooks into AsyncTask.THREAD_POOL_EXECUTOR
already. Lets poke around...
How does it obtain this?
ThreadPoolExecutorExtractor
Who/what uses this?
BaseLayerModule
has provideCompatAsyncTaskMonitor(ThreadPoolExecutorExtractor extractor)
which returns an AsyncTaskPoolMonitor
How does that work? Have a look!
AsyncTaskPoolMonitor
Where is it used?
UiControllerImpl
has method loopMainThreadUntilIdle()
which manually calls asyncTaskMonitor.isIdleNow()
before checking any user registered idlingResources with idlingResourceRegistry.allResourcesAreIdle()
Im guessing with Retrofit we can use the RestAdapter.Builder.setExecutors(...)
method and pass in our own instance (or version) of the AsyncTaskPoolMonitor
using the same http Executor
that Retrofit
is init on Android with
@Override Executor defaultHttpExecutor() {
return Executors.newCachedThreadPool(new ThreadFactory() {
@Override public Thread newThread(final Runnable r) {
return new Thread(new Runnable() {
@Override public void run() {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
r.run();
}
}, RestAdapter.IDLE_THREAD_NAME);
}
});
}
(from here)
And wrap this in the IdlingResource
interface to use in our tests!!
The only question in that as Retrofit
makes the callback using a separate Executor
on the mainThread that relies on the main Looper, this may result in problems but Im assuming for the moment that Espresso is tied into this as well. Need to look into this one.