android - 关于暂停和延期的概念问题

标签 android kotlin kotlin-coroutines

我有一个关于什么时候使用暂停什么时候不使用的问题。我的 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/

相关文章:

android - Android 上的 JavaFx WebView 组件

android - 关于我的Windows帐户名的Android Studio错误?

kotlin - 基于函数式风格的谓词对列表的连续元素进行分区

kotlin - Kotlin 中的 IntArray 与 Array<Int>

android原生发送按钮图标

java - 如何才能比 WorkManager 的 15 分钟上限更快地轮询设备以获取位置数据?

multithreading - 协程可以挂起然后在不同的线程上恢复吗?第一个线程的内存效应是否会传递到第二个线程?

android - 在 Android 项目中使用 StateFlow

Kotlin 协程异步等待序列

android - ExoPlayer 根据 URL 使用哪个 MediaSource