From 3588622bd2724f33adb9f5767237d1c8d8d4b8ed Mon Sep 17 00:00:00 2001 From: Fabian Wiesel Date: Sat, 16 Mar 2024 20:50:46 +0100 Subject: [PATCH] ListenService: Wrap Socket in a Result This way we can handle the IOException in the same place as in the java version, without throwing passing unchecked exceptions --- .../kotlin/de/rochefort/childmonitor/ListenService.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/main/kotlin/de/rochefort/childmonitor/ListenService.kt b/app/src/main/kotlin/de/rochefort/childmonitor/ListenService.kt index 2356165..8dcbbb3 100644 --- a/app/src/main/kotlin/de/rochefort/childmonitor/ListenService.kt +++ b/app/src/main/kotlin/de/rochefort/childmonitor/ListenService.kt @@ -133,8 +133,14 @@ class ListenService : Service() { private var updateCallback: (() -> Unit)? = null private fun doListen(address: String?, port: Int) { val lt = Thread { - val socket = Socket(address, port) - streamAudio(socket).onFailure { e -> + try { + Result.success(Socket(address, port)) + } catch (e : IOException) { + Result.failure(e) + }.fold( + { streamAudio(it) }, // This also may return a failure + { Result.failure(it) } // Or we already have one + ).onFailure { e -> when (e) { is IOException -> Log.e(TAG, "Failed to stream audio", e) else -> Log.e(TAG, "Failed to stream audio for other reason", e)