https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

prasham.h.trivedi

01/10/2019, 7:17 AM
Is there any possibility that
withTimeOut
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
Copy code
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?
e

elizarov

01/10/2019, 8:51 AM
I know of one thing that may be the culprit: in the current implementation
Channel.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.
If that is not your case, then there is some bug. It would be great if you can write a self-contained reproducer and report it to https://github.com/Kotlin/kotlinx.coroutines/issues
d

Dico

01/10/2019, 1:09 PM
You can add
if (!isActive) yield()
In your
consumeEach
loop
isActive
is coming from
CoroutineScope
receiver provided by
launch
2 Views