prasham.h.trivedi
01/10/2019, 7:17 AMwithTimeOut construct doesn’t throw TimeOutCancellationException?
In my android service I am using combination of timeout + channels to send data to specified duration using channels, and the sending operation should end after specified time. I have observed that channels kept sending the data well past timeout limit.
Here is my pseudocode
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
val openChannel = openChannel(interval = interval)
try {
withTimeout(timeMillis = duration) {
openChannel.consumeEach {
doOnTick()
}
}
} catch (e: TimeoutCancellationException) {
openChannel.cancel()
stopService()
}
}
In this code catch isn’t executed sometimes.
This code runs properly on kotlin playground, what is wrong above?elizarov
01/10/2019, 8:51 AMChannel.send only checks for cancellation (and timeout) when it suspends. So, in the case when it never suspends (the other side is fast enough to always receive), then it will not timeout. You can add yield() inside your code — it always checks for cancellation and will throw the corresponding exception.elizarov
01/10/2019, 8:52 AMDico
01/10/2019, 1:09 PMif (!isActive) yield()
In your consumeEach loopDico
01/10/2019, 1:10 PMisActive is coming from CoroutineScope receiver provided by launch