Is there any better way to wrap this function in C...
# coroutines
d
Is there any better way to wrap this function in Caffeine Cache:
Copy code
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
Copy code
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,
Copy code
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
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
Constructing a
CoroutineScope
without explicitly cancelling it is the same as
GlobalScope
. Might as well save the allocation.
👌🏼 1
Yeah, what you said.
d
Thanks!