我有一个关于什么时候使用暂停什么时候不使用的问题。我的 APIRepo 类具有这样的功能 -
override suspend fun retrieveDataFromRemote(): MyResult {
if (utility.checkDeviceInternetConnection()) {
try {
val result = remoteInterface.getData().await()
return ...
} catch (t: Throwable) {
return ...
}
} else {
return ...
}
}
我的远程接口(interface)代码是这样的-
@GET("/data/mydata")
fun getData(): Deferred<Response<MyModel>>
如您所见,我的RemoteInterface
没有suspend
关键字并返回Deferred
。这完全没问题。但是,当我将 suspend
关键字添加到 getData()
时,我没有收到 API 响应。为什么会这样?它与 Deferred
有关系吗?
最佳答案
Retrofit 2.6.0 或更新版本具有内置的suspend
支持。
您可能正在使用 Kotlin Coroutine Adapter
。该库依赖于反射来检测返回类型是否为 Deffered
。参见 here .
这是一个使用 Retrofit 2.6.0 的例子:
interface RemoteInterface{
@GET("/data/mydata")
suspend fun getData(): MyModel
}
在你的 ViewModel 中:
fun retrieveDataFromRemote() {
viewModelScope.launch {
val model = remoteInterface.getData()
// do something with model
}
}
关于android - 关于暂停和延期的概念问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882100/