diff --git a/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3Transport.kt b/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3Transport.kt index c109f0d..d17c22f 100644 --- a/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3Transport.kt +++ b/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3Transport.kt @@ -11,5 +11,7 @@ interface Parsec3Transport { val connectedFlow: StateFlow fun close() + fun reconnect() + suspend fun adapter(): Adapter } \ No newline at end of file diff --git a/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3WSClient.kt b/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3WSClient.kt index 52fbada..4c4ecd0 100644 --- a/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3WSClient.kt +++ b/src/commonMain/kotlin/net.sergeych.parsec3/Parsec3WSClient.kt @@ -22,6 +22,7 @@ class Parsec3WSClient>( private val _connectionFlow = MutableStateFlow(false) private val closeFlow = MutableStateFlow(false) + private val reconnectFlow = MutableStateFlow(false) override val connectedFlow: StateFlow = _connectionFlow @@ -33,6 +34,10 @@ class Parsec3WSClient>( if( closeFlow.value == false ) closeFlow.value = true } + override fun reconnect() { + reconnectFlow.value = true + } + var deferredAdapter = CompletableDeferred>() private set @@ -40,18 +45,22 @@ class Parsec3WSClient>( fun start() { globalLaunch { - client.webSocket(url) { - info { "Connected to $url" } - val a = builder.create { send(Frame.Binary(true, it)) } - _connectionFlow.value = true - launch { closeFlow.collect { if( it == true ) close() } } - deferredAdapter.complete(a) - for (f in incoming) - if (f is Frame.Binary) a.receiveFrame(f.data) - // when we leave connection will be closed. So far we do not close the adapter, - // should we? - _connectionFlow.value = false - deferredAdapter = CompletableDeferred() + while(closeFlow.value != true) { + reconnectFlow.value = false + client.webSocket(url) { + info { "Connected to $url" } + val a = builder.create { send(Frame.Binary(true, it)) } + _connectionFlow.value = true + launch { closeFlow.collect { if (it == true) close() } } + launch { reconnectFlow.collect { if (it == true) close() } } + deferredAdapter.complete(a) + for (f in incoming) + if (f is Frame.Binary) a.receiveFrame(f.data) + // when we leave connection will be closed. So far we do not close the adapter, + // should we? + _connectionFlow.value = false + deferredAdapter = CompletableDeferred() + } } } }