I have this webscocket code: ```fun openWebSocket(...
# ktor
s
I have this webscocket code:
Copy code
fun openWebSocket(scope: CoroutineScope = GlobalScope, consumer: JsonRpcListener) {
        scope.launch {
            <http://httpClient.ws|httpClient.ws>(method = HttpMethod.Get, host = host, port = port, path = path) {
                incoming.consumeAsFlow()
                    .onEach { consumer.run(it) }
                    .collect()
            }
        }
    }
So how do I close the ws from client side?
e
Hey, @Sourabh Rawat.Current coroutine will be blocked by
collect()
, you can try:
Copy code
launch { 
     delay(....) // or suspend for some condition
     outgoing.close()
}
before collect, or run
collect()
in
launch
and close
outgoing
in the origin coroutine
s
I dont this
outgoing
is available in origin coroutine. Assuming
outgoing
means
SendChannel<Frame>
for ws session
e
Yep,
outgoing
should be available on the same scope as
incoming
s
Copy code
fun openWebSocket(scope: CoroutineScope = GlobalScope, listener: JsonRpcListener): () -> Unit {
        val job = scope.launch {
            <http://httpClient.ws|httpClient.ws>(method = HttpMethod.Get, host = host, port = port, path = path) {
                incoming.consumeAsFlow()
                    .onEach { listener(it) }
                    .collect()
            }
        }
        return {
            job.cancel()
        }
    }
So i tried this, using return object (can be renamed to
RemoveListener
or something)? Is it a proper way tho?