【问题标题】:Runtime error for suspend function when implementing launchIn实现launchIn时挂起功能的运行时错误
【发布时间】:2020-06-22 20:41:32
【问题描述】:

launchIn 的实验性实现由于未在 suspend 函数中实现而引发错误。我已经提交了issue 以查看是否有意这样做。

错误

暂停函数“getFeed”只能从协程或其他暂停函数中调用

但是,因为launchIn 是协程的创建者,所以这个错误似乎无效。

feedRepository.getFeed().onEach { results ->
  when (results.status) {
    LOADING -> ...
    SUCCESS -> withContext(Dispatchers.Main) {
      _feedViewState._feed.value = results.data
    }
    ERROR -> ...
  }
}
.flowOn(Dispatchers.IO)
.launchIn(viewModelScope)

原始实现

viewModelScope.launch(Dispatchers.IO) {
  feedRepository.getFeed().collect {  results ->
    when (results.status) {
      LOADING -> ...
      SUCCESS -> withContext(Dispatchers.Main) {
        _feedViewState._feed.value = results.data
      }
      ERROR -> ...
    }
  }
}

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    问题已解决。

    问题在于getFeed 方法是使用suspend 语法实现的。返回 Flow 时不需要 suspend,因为 Flow 以声明方式运行,这意味着 getFeed 定义了调用时将运行的代码。代码将在launchIn 启动时运行,而不是在方法第一次被自身调用时强制运行。

    这个概念在这次演讲中得到了很好的定义,KotlinConf 2019: Asynchronous Data Streams with Kotlin Flow by Roman Elizarov

    之前

    suspend fun getFeed() = flow { ... }

    之后

    fun getFeed() = flow { ... }

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多