@@ -40,6 +40,7 @@ import kotlinx.coroutines.delay
4040import kotlinx.coroutines.flow.MutableSharedFlow
4141import kotlinx.coroutines.launch
4242import kotlinx.coroutines.suspendCancellableCoroutine
43+ import kotlinx.coroutines.withTimeout
4344import kotlinx.serialization.decodeFromString
4445import kotlinx.serialization.encodeToString
4546import kotlinx.serialization.json.Json
@@ -62,6 +63,7 @@ import java.util.Date
6263import javax.inject.Inject
6364import javax.inject.Named
6465import javax.inject.Singleton
66+ import kotlin.time.Duration.Companion.seconds
6567
6668/* *
6769 * SignalClient to LiveKit WS servers
@@ -184,10 +186,19 @@ constructor(
184186 .addHeader(" Authorization" , " Bearer $token " )
185187 .build()
186188
187- return suspendCancellableCoroutine {
188- // Wait for join response through WebSocketListener
189- joinContinuation = it
190- currentWs = websocketFactory.newWebSocket(request, this )
189+ return withTimeout(5 .seconds) {
190+ suspendCancellableCoroutine { cont ->
191+ // Wait for join response through WebSocketListener
192+ joinContinuation = cont
193+ // When a coroutine is canceled, WebSocket must be interrupted.
194+ cont.invokeOnCancellation {
195+ LKLog .w { " connect cancelled, abort websocket" }
196+ currentWs?.cancel()
197+ currentWs = null
198+ joinContinuation = null
199+ }
200+ currentWs = websocketFactory.newWebSocket(request, this @SignalClient)
201+ }
191202 }
192203 }
193204
@@ -868,7 +879,7 @@ constructor(
868879 pingJob = null
869880 pongJob?.cancel()
870881 pongJob = null
871- currentWs?.close(code, reason )
882+ currentWs?.cancel( )
872883 currentWs = null
873884 joinContinuation?.cancel()
874885 joinContinuation = null
0 commit comments