Skip to content

Commit

Permalink
Merge pull request #35 from kitakkun/feature/automatic_reconnect
Browse files Browse the repository at this point in the history
Automatically reconnect after being disconnected from the server
  • Loading branch information
kitakkun authored Apr 23, 2024
2 parents 3287bc8 + 513ea1f commit 7eba5d1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

class BackInTimeWebSocketClientConnector(host: String, port: Int) : BackInTimeConnector {
class BackInTimeWebSocketClientConnector(host: String, port: Int, private val automaticReconnect: Boolean = true) : BackInTimeConnector {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private val client: BackInTimeWebSocketClient = BackInTimeWebSocketClient(host = host, port = port)
override val connected: Boolean get() = client.isConnected
Expand All @@ -27,6 +27,12 @@ class BackInTimeWebSocketClientConnector(host: String, port: Int) : BackInTimeCo
delay(3000L)
}
mutableIsConnectedFlow.value = true
// reconnect after disconnection
if (automaticReconnect) {
client.closeReason().await()
mutableIsConnectedFlow.value = false
connect()
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,17 @@ class BackInTimeWebSocketClient(
suspend fun connect(): Result<Unit> {
return try {
session = client.webSocketSession(host = host, port = port, path = "/backintime")
session?.closeReason?.invokeOnCompletion {
session = null
}
Result.success(Unit)
} catch (e: Throwable) {
Result.failure(e)
}
}

fun closeReason() = session?.closeReason ?: error("Not connected")

fun receiveEventAsFlow() = session?.incoming?.receiveAsFlow()
?.filterIsInstance<Frame.Text>()
?.map {
Expand Down

0 comments on commit 7eba5d1

Please sign in to comment.