I'm trying to model a 'lazy suspend' task. For the...
# coroutines
c
I'm trying to model a 'lazy suspend' task. For the moment, it's encoded as:
val task = scope.async {
foo()
}
suspend fun bar() {
// All calls require the task to be over,
// however only the first one(s) will really suspend,
// since it will be ready for the others
val foo = task.await()
doSomething(foo)
}
The problem is that this requires a
scope
to be available when the task is instantiated. Since I do not care whether the task starts when it is instantiated or when the first call to
bar
is made, is there a way to adapt this pattern without requiring the
scope
?
p
You can use the Global scope if you are not interesting in cancelling it.
s
Or make
task
a lambda taking a CoroutineSccope as a param and returning a Deferred.
val task: (CoroutineScope) -> Deferred<X> = { scope -> async { foo() } }
Then in bar() you can call it like this:
val foo: X = coroutineScope { task(this).await() }
g
To store the result after the first call and avoid using GlobalScope, you could also wrap the API and use the first scope it gets awaited with
c
Thanks, all of these look pretty good.