Sam
05/02/2025, 9:51 AMAsyncCache
for use with Kotlin coroutines. One of the bugs is with coroutine context being leaked between coroutines, and the other is related to cancellation. Hope it can help others avoid the same issues in future! https://sam-cooper.medium.com/0b6e9fecad11phldavies
05/02/2025, 10:23 AMSam
05/02/2025, 10:26 AMSam
05/02/2025, 10:28 AMSam
05/02/2025, 10:30 AMWout Werkman
05/07/2025, 12:33 PMWhileSubscribed
semantics. Such that it's canceled as soon as there is no listeners for that value anymore. Perhaps these caching libraries should provide this out of the box? :)Wout Werkman
05/07/2025, 12:36 PMcoroutineScope { }
block.
I was surprised to find no link between this article and https://sam-cooper.medium.com/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b.
Because leaking `CoroutineScope`s is exactly what leads to cancellation exceptions leaking into other coroutine trees, which leads to the necessity of ensureActive()
instead of rethrowing.
I have one additional tip though. I urge everyone who makes suspending higher order functions to give them a CoroutineScope
receiver. There are many footguns that occur when it's not there.
Now you could still accidentally leak cancellation as follows:
someFlow().collectLatest {
coroutineScope {
cache.getOrPut("foo") { async { computationB() }.let { computationA() + it.await() }
}
}
Here if the computation get's canceled and restarted because of an emission into the flow, then the cancellation exception from the previous emission gets thrown into the next.
`kotlinx.coroutine`'s collectLatest
is missing the receiver as well, and <http://[`Flow.collectLatest`%20is%20error-prone%20because%20of%20no%20`CoroutineScope`%20路%20Issue%20#3533%20路%20Kotlin/kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines/issues/3533)|we regret this>.Sam
05/07/2025, 2:20 PMWhileSubscribed
solution is a really great one very nice I think I've used that before, though I'd completely forgotten about it until you mentioned it. Might have to write an article on that too!Sam
05/07/2025, 2:21 PM