https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Czar

03/26/2020, 2:57 PM
Hi, I have something like this:
Copy code
fun serviceSseRequest(sseEmitter: SseEmitter) {
  
  val liveOutput: Channel<String> = doSomethingInBackground()
  
  liveOutput.consumeAsFlow().collect { sseEmitter.emitServerSideEvent(it) }
}
How do I determine that there won't be any more messages in the channel? Maybe there is some other component that I can use instead of the channel here?
a

araqnid

03/26/2020, 2:59 PM
doSomethingInBackground() should presumably close the send side of the channel (just
close()
)
c

Czar

03/26/2020, 3:00 PM
if I close it in the background job I face situation where not all messages were consumed by the slow reader.
d

Dennis

03/26/2020, 3:31 PM
A Channel is Rendezvous by default, right? Your producer will be slowed down by your consumer.
Copy code
Conceptually, a close is like sending a special close token to the channel. The iteration stops as soon as this close token is received, so there is a guarantee that all previously sent elements before the close are received
b

bdawg.io

03/26/2020, 5:46 PM
Make sure it's being told to close
close()
and not
cancel()
since that would indeed cause your consumer not to receive all the values
c

Czar

03/26/2020, 7:29 PM
Thanks, I'll look into these suggestions