Kotlin Coroutine - Keeping Channel Send Event Synchronous
18:41 22 Oct 2019

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) : ... {

 ...

  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.

kotlin channel coroutine