我刚开始使用协程/流(以及一般的 kotlin),我正在努力将回调流转换为共享流。
我将下面的简单示例放在一起只是为了展示我尝试过的内容,但没有成功。我的代码更复杂,但我相信这个例子反映了我想要实现的问题。
fun main() = runBlocking {
getMySharedFlow().collect{
println("collector 1 value: $it")
}
getMySharedFlow().collect{
println("collector 2 value: $it")
}
}
val sharedFlow = MutableSharedFlow<Int>()
suspend fun getMySharedFlow(): SharedFlow<Int> {
println("inside sharedflow")
getMyCallbackFlow().collect{
println("emitting to sharedflow value: $it")
sharedFlow.emit(it)
}
return sharedFlow
}
fun getMyCallbackFlow(): Flow<Int> = callbackFlow<Int> {
println("inside callbackflow producer")
fetchSomethingContinuously {
println("fetched something")
offer(1)
offer(2)
offer(3)
}
awaitClose()
}
fun fetchSomethingContinuously(myCallBack: ()->Unit) {
println("fetching something...")
myCallBack()
}
这个想法是fetchSomethingContinuously
只调用一次,与 sharedFlow 的收集器数量无关。但正如您从输出中看到的那样,收集器永远不会获取值:
inside sharedflow
inside callbackflow producer
fetching something...
fetched something
emitting to sharedflow value: 1
emitting to sharedflow value: 2
emitting to sharedflow value: 3
我查看了shareIn运算符,但不确定如何准确使用它。
我怎么能做到这样的事情?任何提示将不胜感激。