I'm looking for examples of how to combine Ktor We...
# ktor
e
I'm looking for examples of how to combine Ktor WebSocket client with Asynchronous Flow. I have a pub/sub-like setup where I send a message to server in order to subscribe for values, but I'm completely lost on how to set this up. I can share what I have so far, but it's quite bad. I doesn't have to be with Flow, but I figured it would fit quite well here.
c
Are you talking about coroutines flow?
You can simply make a flow from the incoming frames channel
e
Yes coroutines flow. How?
c
Copy code
client.wss("....") {
    incoming.consumeAsFlow() ...
}
?
e
Nice. How can I return it? My code is a library where others can subscribe (and get a flow back)
c
Well, it depends
If you need it to be cold then you need something like this:
Copy code
fun HttpClient.webSocketFlow(urlString: String): Flow<Frame> = flow {
        ws(urlString) {
            emitAll(incoming)
        }
    }
If you need a hot flow, then
Copy code
client.webSocketSession(host = "xxx", path = "/endpoint").incoming.consumeAsFlow()
The first is cool, you may also combine with flow retry functions to reconnect
e
Thank you. I will have to experiment with this
I've been testing out some approaches, but wasn't able to use
consumeAsFlow
because I want multiple listeners. I have managed to create working solution, but it looks messy: https://gist.github.com/eirikb/41910638c2acef9f8f84c43f507f6023 . It also has some issues