I am just starting with the usage of coroutines/flow (and kotlin in general) and I am struggling to convert a callbackFlow to a sharedFlow.
I have put together the simple example below just to show what I have tried, without success. My code is more complex but I believe this example reflects what are the issues of what I am trying to achieve.
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()
}
The idea is that the fetchSomethingContinuously is only called once, independent the number of collectors of the sharedFlow. But as you can see from the output, collectors never gets the values:
inside sharedflow
inside callbackflow producer
fetching something...
fetched something
emitting to sharedflow value: 1
emitting to sharedflow value: 2
emitting to sharedflow value: 3
I looked in the shareIn operator, but not sure how to use it exactly.
How could I achieve something like this? Any tips would be very appreciated.