For desktop applications callbacks will happen on the same thread that executed the HTTP request.
我试图通过研究 Retrofit 源代码(特别是 RestAdapter.java
)并查看许多其他类似的 SO 问题(例如 this )来理解这一点,但我仍然感到困惑。
如果我有一个调用 void getUserPhoto(@Path("id") int id, Callback<Photo> cb)
的后台线程(例如),这个库究竟如何在该线程上执行回调?
最佳答案
如果您将相同的执行器传递给 RestAdapter
,那么我们说:
ExecutorService backgroundExecutor = Executors.newCachedThreadPool();
restAdapterBuilder.setExecutors(backgroundExecutor, backgroundExecutor);
然后回调Runnable
将在此后台执行器上执行,这意味着您将在同一线程中收到回调,否则该线程将被关闭或重用,并且回调将发生在与该后台执行器不同的线程上执行http请求的一个。
当Retrofit
检查您是否在桌面应用程序或Android应用程序上运行它时,它会检查是否存在来自android sdk的现有包,然后获取http请求和回调的执行器将会发生,即如果您在 Android 上运行,它将在主线程上运行回调 Runnable
。如果您在非 Android 上运行,它将获得同步执行器(与用于 http 请求的相同),除非您不传递其他内容。如果您自己不这样做,这些是构建的默认平台设置。
关于android - 在Retrofit中, "callbacks will happen on the same thread that executed the HTTP request"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29107021/