jozefdransfield
09/12/2022, 2:39 PMNick Allen
09/13/2022, 11:57 PMflow { emit(1); emit(2) }
you are creating something that will run that lambda every time anything calls collect. Every collector will run code that emits a 1 and a 2.
When you call myChannel.receiveAsFlow()
, it's the basically
flow {
for(item in myChannel) {
emit(item)
}
}
Every collector is running the same code, but items are removed from the Channel
as they are received so each collector gets its own separate items.
Consider:
var x = 0
val f = flow { x++; emit(x) }
Every collector would get a different value as x increases.
If you want to "share" the items of the Channel
, you can share the resulting Flow
:
myChannel.consumeAsFlow()
.shareIn(scope, SharingStarted.WhileSubscribed())
which will only collect from the channel once. You'll want to adjust the started
and replay
params to fit your needs.