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

yschimke

08/03/2019, 10:02 AM
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

gildor

08/04/2019, 4:39 AM
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

yschimke

08/04/2019, 5:15 AM
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

louiscad

08/04/2019, 5:16 AM
@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.
11 Views