I am working in Kotlin to create a UDP socket between an Android client and a server. For receiving messages, I'm using a coroutine, and the code itself works correctly, checking for every incoming message.
My objective now is to set a timeout (or something similar) of 30 seconds to detect if the communication has been lost. If the timeout is reached, I do NOT want the loop to block; I want it to continue to receive any incoming messages. I just want to log or display an appropriate message in a toast.
val myCoroutineScope = lifecycleScope
if (myCoroutineJob == null || myCoroutineJob?.isCompleted == true) {
// Connection to the server
myCoroutineScope.launch {
withContext(Dispatchers.IO) {
client = Client()
}
// A listener function is created, it is used to handle the data as needed
client?.dataReceivedListeners?.add { data ->
try {
receivedText = decompress(data)
val jsonObject = JSONObject(receivedText.toString())
# RECEIVED MESSAGES HANDLING....
}
} catch (e: JSONException) {
# ERROR HANDLING ........
}
}
}
}
You can use withTimeoutOrNull
for that. Note that it is a suspend function. It can be used like that:
val value = withTimeoutOrNull(5000) {
// ... long running operation
"Hello"
}
value will be either "Hello" or null
in case the timeout of 5000ms was exceeded.