在 Retrofit 中,"callbacks will happen on the same thread that executed the HTTP request" 是什么意思?

In Retrofit, what is meant by "callbacks will happen on the same thread that executed the HTTP request"?

Retrofit Documentation 声明如下:

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 上 运行ning,它将在主线程上 运行 回调 Runnable。如果您 运行ning 在非 Android 上,它将获得同步执行器(与用于 http 请求的相同),除非您不传递其他内容。这些是构建的默认平台设置,如果你不自己做的话。