Kotlin Coroutine - Keeping Channel Send Event Synchronous

Viewed 390

I have a class which listens to events coming from a socket at a very fast pace. I would like to feed these events into a coroutine Channel. The following code is used:

class MyClass(channel: Channel<String>) : ... {

 ...

  override onMessageReceived(message: String) {
     MyScope.launch {
        channel.send(message)
     }
  }

}

This does not work since sometimes the events come in so fast that they end up getting posted out of order due to the launch spawning a new coroutine and everything happening in parallel. How can I ensure the order of the send is synchronous?

I tried newSingleThreadContext which did work however it is considered experimental and has a note saying it will be removed eventually. I am looking for a more solution that is more correct and complete.

1 Answers

Instead of launching the sends in parallel, you should use a Channel with a capacity of Channel.UNLIMITED, and have onMessageReceived use offer instead of send.

This is a lot cheaper than launching a new job for each send, and the channel will preserve the order

Related