https://kotlinlang.org logo
Title
d

dave08

07/28/2019, 2:47 PM
Is there any better way to wrap this function in Caffeine Cache:
suspend fun <K: Any, V> AsyncCache.getSuspending(key: K): V {
    val outerContext = coroutineContext
    return get(key) { k, executor ->
        val innerContext = outerContext + Job() + executor.asCoroutineDispatcher()
        CoroutineScope(innerContext).async {
            loadValue(k) // loadValue is a suspend function defined elsewhere
        }.asCompletableFuture()
    }.await()
}
d

Dominaezzz

07/28/2019, 2:58 PM
suspend fun <K: Any, V> AsyncCache.getSuspending(key: K): V {
    val outerContext = coroutineContext
    return get(key) { k, executor ->
        val innerContext = outerContext + Job() + executor.asCoroutineDispatcher()
        GlobalScope.async(innerContext) {
            loadValue(k) // loadValue is a suspend function defined elsewhere
        }.asCompletableFuture()
    }.await()
}
or even better,
suspend fun <K: Any, V> AsyncCache.getSuspending(key: K): V {
    val outerContext = coroutineContext
    return get(key) { k, executor ->
        val innerContext = outerContext + Job() + executor.asCoroutineDispatcher()
        GlobalScope.future(innerContext) {
            loadValue(k) // loadValue is a suspend function defined elsewhere
        }
    }.await()
}
d

dave08

07/28/2019, 3:00 PM
But then I loose the parent-child Job relationship (since we're using
GlobalScope
)? Or did I misunderstand?
Unless providing
innerContext
does the same?
d

Dominaezzz

07/28/2019, 3:01 PM
Constructing a
CoroutineScope
without explicitly cancelling it is the same as
GlobalScope
. Might as well save the allocation.
👌🏼 1
Yeah, what you said.
d

dave08

07/28/2019, 3:05 PM
Thanks!