【发布时间】:2021-10-20 16:54:06
【问题描述】:
我是 Kotlin 协程和流程的新手。我正在使用数据存储来存储一些布尔数据,而从数据存储中读取数据的唯一方法是根据文档使用流。
我的 ViewModel 中有这段代码
fun getRestroProfileComplete(): Boolean {
var result = false
viewModelScope.launch {
readRestroDetailsValue.collect { pref ->
result = pref.restroProfileCompleted
}
}
Log.d(ContentValues.TAG, "getRestroProfileComplete outside: $result")
return result
}
在我的片段 onCreateView 方法中,这段代码
if(restroAdminViewModel.getRestroProfileComplete()){
Log.d(TAG, "Profile Completed")
profileCompleted(true)
}else{
Log.d(TAG, "Profile not completed ")
profileCompleted(false)
}
有时我从数据存储中获取数据,有时它总是错误的。
我知道 getRestroProfileComplete 方法函数不等待启动代码块完成并给出默认的错误结果。
最好的方法是什么?
【问题讨论】:
-
您的视图模型应该使用布尔值向视图呈现一个流(或类似的)。
-
你已经创建了一个竞争条件,当你的函数返回时协程可能还没有完成第一个值的收集。解释和解决方法见这里:stackoverflow.com/a/68370029/506796
标签: kotlin kotlin-coroutines flow