Chris Fillmore
04/21/2022, 4:16 PMsuspend fun sendAndWait(message: Message): Message = withTimeout(5000) {
launch {
send(message)
}
// 'incoming' is a Flow<Message>
incoming.first { /* logic here which matches outbound messages with inbound ones by some matching id */ }
}
The timeout never works. It never times out, I don’t get an exception. There are two suspension points: send(message)
and incoming.first { }
. Is there something I’m misunderstanding about timeouts? withTimeout
has otherwise worked for me; I’m not sure what’s different in this case. Any ideas?Jacob
04/21/2022, 4:21 PMsend(message)
counts as a suspension point when it's being `launch`edChris Fillmore
04/21/2022, 4:21 PMFlow.first()
should work, I thoughtsimon.vergauwen
04/21/2022, 5:30 PMincoming
come from? If the Flow<Message>
is not cancellable, then`withTimeout` will not return before it's finished.Chris Fillmore
04/21/2022, 5:55 PMincoming
is a SharedFlow with incoming websocket frames. I am using Ktor/OkHttp websockets.
I understand that cancellation can occur at any suspension point. But I guess I am confused by the statement in the docs:
All the suspending functions inI am expectingare cancellable.kotlinx.coroutines
Flow.first()
to be cancellable. But perhaps I need a workaround like
suspend fun sendAndWait(message: Message): Message = withTimeout(5000) {
val job = async {
launch {
send(message)
}
incoming.first()
}
job.await()
}
Chris Fillmore
04/21/2022, 5:56 PMChris Fillmore
04/21/2022, 6:12 PMfun main(args: Array<String>) = runBlocking {
val incoming = MutableSharedFlow<Unit>()
val result = withTimeout(3000) {
incoming.first()
}
println("Got result: $result")
}
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 3000 ms
simon.vergauwen
04/22/2022, 12:45 PMI am expectingThat might depend, for example I think the following is prone to hanging.to be cancellable. But perhaps I need a workaround likeFlow.first()
flow<Int> {
withContext(NonCancellable) {
delay(Long.MAX_VALUE)
emit(1)
}
}.first()
julian
04/22/2022, 5:53 PMChris Fillmore
04/22/2022, 5:54 PMChris Fillmore
04/22/2022, 5:55 PMjulian
04/22/2022, 5:57 PM