【发布时间】:2022-12-06 00:09:25
【问题描述】:
我想问你为什么它有效?
通常当我使用collectLatest和flow时,我的数据没有按时收集,返回值为空。我必须使用async-await协程,但我读过它会阻塞主线程,所以效率不高。我进行了研究并使用 sharedflow 找到了解决方案。
之前:
suspend fun getList: List<Items> {
CoroutineScope(Dispatchers.Main).launch {
async {
flow.collectLatest {
myItems = it
}
}.await()
}
return myItems
}
或者没有await-async,它返回emptyList
现在:
suspend fun getList: List<Items> {
val sharedFlow = flow.conflate().shareIn(
coroutineScopeIO,
replay = 1,
started = SharingStarted.WhileSubscribed()
)
return sharedFlow.first()
}
合并意味着:
Conflates flow emissions via conflated channel and runs collector in a separate coroutine. The effect of this is that emitter is never suspended due to a slow collector, but collector always gets the most recent value emitted.
我不确定我是否理解清楚。当我合并流程时,我只是创建单独的协程来发出我的另一个函数中的内容,如我的示例shareIn().first() 并使用这个暂停的变量sharedFlow,所以会产生与我所做的相同的效果asnyc-await,但在那种情况下我不会阻塞主线程,但只会阻塞我的确切*parentCoroutine-or-suspendFunction?
SharingStarted.WhileSubscribed() 它只是意味着在订阅时开始发射。
【问题讨论】:
标签: android kotlin kotlin-coroutines kotlin-stateflow kotlin-sharedflow