android - 如何在 Android 的生命周期感知协程范围内返回函数值?
问题描述
fun returnValue(): Int {
viewModelScope.launch {
return 1 // Something like this
}
}
我想在上面的 viewModelScope 中返回一些值。我不希望我的功能被挂起。我该如何做到这一点?
解决方案
如果returnValue()
不能挂起功能,基本上只有两种选择:
- 将返回类型转换为
Deferred<Int>
并让调用者负责稍后处理返回值。身体变成:
fun returnValue(): Deferred<Int> = viewModelScope.async {
return@async 1
}
- 阻塞线程直到值可用:
fun returnValue(): Int {
return runBlocking(viewModelScope.coroutineContext) {
return@runBlocking 1
}
}
推荐阅读
- spring - 为什么访问令牌不再有到期时间?
- java - 具有很多字段的不同类型的实体 - 建模它的最佳方法是什么?
- scala - 如何在 scala 运行时知道不同的连接类型火花
- host - 计算子网位和主机位
- ruby-on-rails - 无法在 Rails 5.2 中创建记录
- ios - 如何从 URL 将 Live Photo 保存到图库?
- java - B 类中构造函数的参数 0 需要 A 类类型的 bean,但无法找到
- git - 在 git commit 但不是在本地隐藏或更改一行(或多行)的值
- json - 如何在 MongoDB 中查询子对象内的数据?
- java - java.net.SocketException:连接重置 - 尝试在 java8 中使用 https restful api 时出现异常