https://kotlinlang.org logo
Title
a

Ayomide

01/09/2021, 6:01 PM
Hey, I'm trying out Ktor's WebSocket client library. It returns incoming messages from a web socket as a 
SharedFlow
 - I'm trying to figure out how to keep the web socket session (
DefaultClientWebSocketSession
) running in the background so that I can collect the 
SharedFlow
 messages and display them on screen as they stream in. I tried using 
coroutineScope.launch{}
  but it seems like the web socket session would stop as soon as the coroutine scope block ended. Not sure what to do to make sure the process runs forever in the background
r

Rob

01/09/2021, 6:30 PM
Since the Ktor client callback is a suspend function you can just loop over the incoming frames.
Another way to prevent the callback from returning is by calling
awaitCancellation()
at the end of the callback.
Or if you prefer to use collect()
a

Ayomide

01/09/2021, 7:47 PM
Thanks! await cancellation worked, and I also tried consuming incoming as flow. Also, just having it as the last statement in a coroutine scope worked. Now to figure out how to send messages from other places while I am receiving messages!