Martin Devillers
12/18/2018, 10:11 AMgildor
12/18/2018, 10:17 AMMartin Devillers
12/18/2018, 10:18 AMwithContext
can’t be cancelled. But the coroutine started by launch
can.withContext
gildor
12/18/2018, 10:19 AMMartin Devillers
12/18/2018, 10:20 AMwithContext
coroutine would just have to be null, since it’s cancelled anyways.gildor
12/18/2018, 10:21 AMMartin Devillers
12/18/2018, 10:23 AMgildor
12/18/2018, 10:24 AMlaunch {
try {
val message = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
Thread.sleep(Long.MAX_VALUE)
"Hello World!"
}
}
} finally {
//do some required operation in any case
}
}
elizarov
12/18/2018, 11:02 AMRohan Maity
12/18/2018, 11:22 AMMartin Devillers
12/18/2018, 12:11 PMwithContext
inherits the parent job from launch
, so it will receive the cancellation. The issue is that the cancellation won’t do anything because the coroutine doesn’t handle it. This coroutine will therefore continue running, and will keep the reference to the activity through its continuation.Rohan Maity
12/18/2018, 12:45 PMgildor
12/18/2018, 12:49 PMstreetsofboston
12/18/2018, 12:52 PMwithContext
does not cancel and keeps running.
But this block of code does not have a reference to anything in the Activity. This block of code doesn't leak.
But the launch
has a call to this@CoroutineActivity.findViewById
which can leak the Activity.
Does a coroutine not cancel if one of its child-coroutines are not cancelled?
Could a cancel request interrupt a running Thread?gildor
12/18/2018, 1:08 PMRohan Maity
12/18/2018, 1:13 PMgildor
12/18/2018, 1:15 PMVsevolod Tolstopyatov [JB]
12/18/2018, 1:18 PMCould a cancel request interrupt a running Thread?No. Interruptions are asynchronous by its nature and can be delivered to the “wrong” coroutine. E.g. what if you run he following
val job = launch(singleThreadDispatcher) {
Thread.sleep(1)
}
val job2 = launch(singleThreadDispatcher) {
...
}
job.cancel() // let's assume "cancel" interrupts thread where coroutine is running
How can you guarantee that interrupt will be delivered while job
is executing, not job2
?streetsofboston
12/18/2018, 1:19 PMlaunch
fail to be cancelled because its child-routine in withContext
is never cancelled?Rohan Maity
12/18/2018, 1:20 PMgildor
12/18/2018, 1:26 PMstreetsofboston
12/18/2018, 1:37 PMgildor
12/18/2018, 3:21 PM