Home > OS >  Setting a timeout wrapper over SharedFlow's .first()
Setting a timeout wrapper over SharedFlow's .first()

Time:02-26

I have a client program which makes requests to the server for a few properties. One of these properties is an Int, called ID. I'd like to send the request to the server and get the value back in one clean suspending function with a timeout:

suspend fun requestID(str: String):Int? {

... send message to server

... and get the reply

... return null if timed out

}

val id = connection.requestID("bob")

I tried doing it via a SharedFlow with a withTimeout(), but shared flow's firstOrNull() function isn't cancellable and is a suspending function. Anyone have any tips?

CodePudding user response:

Kotlin provides withTimeoutOrNull() that does exactly this:

val id = withTimeoutOrNull(5000) {
    requestIdFromServer(str)
}

Where requestIdFromServer() is a suspend function that retrieves the data. In the case of timeout the coroutine running the request will be cancelled.

  • Related