【发布时间】:2021-01-20 06:58:57
【问题描述】:
这是我已经知道的:
Retrofit 有enqueue 函数和execute 函数。 enqueue 函数在不同的(后台)线程上执行,然后使用回调返回响应。 execute 函数在调用线程上执行并直接返回响应。 enqueue 可以在 UI 线程上调用,而 execute 不应该在 UI 线程上调用。
但我现在想知道,以下两个选项中哪个更好。
在普通函数中调用enqueue:
fun makeRequest() {
getCall().enqueue(
object : Callback<ResponseBody> {
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (response.isSuccessful) {
//unsuccessful
}
//successful
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//failed
}
}
)
}
或在后台线程的挂起函数中调用execute:
suspend fun makeRequest() = withContext(Dispatchers.IO) {
val call = getCall()
try {
val response = call.execute()
if (!response.isSuccessful) {
//unsuccessful
}
//successful
} catch (t: Throwable) {
//failed
}
}
其中哪一个更可取?
【问题讨论】:
标签: android kotlin retrofit2 kotlin-coroutines