https://kotlinlang.org logo
#ktor
Title
# ktor
e

eirikb

02/06/2020, 2:24 PM
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

cy

02/06/2020, 2:26 PM
Are you talking about coroutines flow?
You can simply make a flow from the incoming frames channel
e

eirikb

02/06/2020, 2:27 PM
Yes coroutines flow. How?
c

cy

02/06/2020, 2:28 PM
Copy code
client.wss("....") {
    incoming.consumeAsFlow() ...
}
?
e

eirikb

02/06/2020, 2:32 PM
Nice. How can I return it? My code is a library where others can subscribe (and get a flow back)
c

cy

02/06/2020, 2:37 PM
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

eirikb

02/06/2020, 2:54 PM
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
4 Views