Is there an established pattern for memoizing asyn...
# coroutines
y
Is there an established pattern for memoizing async tasks? within some coroutine scope? if the scope is per request, it would be great to avoid duplicate work etc
I'm assuming the default is just a synchronized MutableMap<K, Deferred<V>> and using getOrPut with async?
g
Yes, async and Deferred is the way to do that. Map and getOrPut is the way to cache many values. But careful with thread safety of map itself, if you access it from different thread you need a way to do that concurrently (concurrent map, or dispatch access to particular thread
This SuspendLazy violates structured concurrency (and as result of it will leak). You should pass scope to constructor instead of dispatcher and make function extension for coroutine scope
y
That's the kicker. the structured concurrency has nice properties like cancelling when overall scope fails, be nice if this was a Scope feature?
l
@gildor My use case didn't need it as I was only using it at top-level, but you're right. I updated
suspendLazy
(and the permalink above) to be an extension for
CoroutineScope
so it can't break structured concurrency anymore.