connect
Establishes a WebSocket connection to the server specified by url.
This method launches a coroutine in coroutineScope and attempts to open a WebSocket session. Once connected, it listens for incoming messages and emits them into incomingMessages as a SharedFlow of strings.
Important notes:
This method is asynchronous and returns immediately; use incomingMessages to observe messages.
If the connection fails, the exception will be caught and logged, and session will be null.
Only one connection is maintained at a time. Calling connect while a session is already active will attempt to open a new session but does not automatically close the previous one.
To properly close the connection, call disconnect.
Example usage:
val wsManager = WebSocketManager("wss://example.com/socket")
wsManager.connect()
wsManager.incomingMessages.onEach { message ->
println("Received: $message")
}.launchIn(CoroutineScope(Dispatchers.Default))Content copied to clipboard