Member-only story
Kotlin Channel and WebSocket Complete Example (Also Why Not Flow)
In Android development WebSockets are not as common as REST calls that’s why I find it very useful to share a full example of WebSocket implementation with Kotlin Channel and coroutines. Also some additional reasoning on why I am using Channel and not Flow.

First step would be to pick which WebSocket APIs we are using. We can use raw Java APIs or the OkHttp library to support our implementation.
I am using the OkHttp library simply because I am familiar with it and I already have it in my production project to provide Retrofit dependencies for the REST calls.
Let’s dive into the code.
First let’s plug in those dependencies to your Gradle file.
implementation "com.squareup.okhttp3:okhttp:4.9.0"
Now we need to define the WebSocket listener class.
Let’s go over the listener to see what’s going on in this code.
Info: For the example purposes I am sending the messages onOpen because the socket test server I am using is an echo server.
First thing to note is that we created an event channel in the socket. The digit 10 we are passing indicates that our channel buffer is 10 events. You define what seems most suitable for your use case. We have also created a simple data class SocketUpdate to wrap the message into an object for our use.
Now that we have the listener we need to open the socket and attach it.
We are going to call startSocket method that will return Channel<SocketUpdate> that we are going to collect from.
And the only part remaining is to create all our classes according to the MVVM…