Hello, I currently have a `Channel` representing a...
# flow
m
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
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
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
Then maybe you can use receiveAsFlow.
channel.recieveAsFlow()
and use
channel.offer()
to send the jobs
m
That seems to work, thank you. Although still keeps me needing a
Channel
. I thought I could use Flows to replace Channels completely.
f
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