https://kotlinlang.org logo
#flow
Title
# flow
m

Marcin Wisniowski

06/01/2020, 7:20 PM
Hello, I currently have a
Channel
representing a job queue, and a method that `send`s a new job to the queue. A separate coroutine is an infinite
receive
loop that processes the jobs. How would I represent that with Flow? I'm not sure how to use the
flow {}
builder since I don't know what to
emit
upfront, the jobs come from outside.
f

fatih

06/01/2020, 7:57 PM
Normally, (before StateFlow) you would have done it with
ConflatedBroadcastChannel.asFlow()
. You can just change the channel value and all collectors will be notified. But it is better to do it with
StateFlow
. You could create a
MutableStateFlow
instead of channel and change its value with
mutableStateFlow.value
and all the collectors will be notified
m

Marcin Wisniowski

06/01/2020, 8:04 PM
Ok, but MutableStateFlow seems to only support having one value. My queue might have multiple jobs waiting for processing. My use case is having only one collector and potentially many producers adding jobs to the queue.
f

fatih

06/01/2020, 8:13 PM
Then maybe you can use receiveAsFlow.
channel.recieveAsFlow()
and use
channel.offer()
to send the jobs
m

Marcin Wisniowski

06/01/2020, 8:41 PM
That seems to work, thank you. Although still keeps me needing a
Channel
. I thought I could use Flows to replace Channels completely.
f

fatih

06/01/2020, 9:30 PM
Np simple smile Happy to help. Btw if you only care about the last job then I think
StateFlow
could also be used in your case. Otherwise if you want in a synchronous way then you can replace your channel with
SharedFlow
when it is ready (https://github.com/Kotlin/kotlinx.coroutines/issues/2034) The thing is you need to back
Flow
with a channel since flow itself does not keep any cache value and you cannot send value from outside without channel. But if you use
StateFlow
or
SharedFlow
then you don’t need a channel
4 Views