Hello All, I might be missing something but what i...
# flow
j
Hello All, I might be missing something but what is the difference between a flow generated from flow { … } and a ReceiveChannel.receiveAsFlow() im seeing some behavour i dont understand, namely if i create multiple new flows based on filters, the regular flow one receives all the messages, this isnt the case when they come from a receive channel. I have a unit test to replicate what im seeing if it helps?
n
When you write
flow { 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
Copy code
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:
Copy code
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
:
Copy code
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.