sam
08/26/2019, 6:35 PMsuspend fun foo() { async { ... } }
. I’d like to use async inside foo, and inherit from whatever scope foo was called with.withoutclass
08/26/2019, 6:38 PMfoo
be an extension function of CoroutineScope
octylFractal
08/26/2019, 6:39 PMfoo
. to enforce this, kotlin only offers the CoroutineScope
in suspend functions via `coroutineScope { }`:
suspend fun foo() {
coroutineScope { async { ... } }
}
This means that foo
won't return until the async task completes.
Or, you can have foo
be an extension on CoroutineScope
, but then it shouldn't be a suspend
function, and should not use any suspend operators of its own (except inside of whatever coroutine you launch on the provided scope)sam
08/26/2019, 6:40 PMsuspend fun CoroutineScope.foo() { delay(1000) }
octylFractal
08/26/2019, 6:41 PMsam
08/26/2019, 6:42 PMfun CoroutineScope.foo() { delay(1000) }
octylFractal
08/26/2019, 6:42 PMsam
08/26/2019, 6:42 PMinterface Foo { suspend fun process() }
suspend fun process() {
coroutineScope {
val defs = urls.map {
async(<http://Dispatchers.IO|Dispatchers.IO>) {
}
}
defs.awaitAll()
}
}
withoutclass
08/26/2019, 6:44 PMcoroutineScope{}
will create a brand new scope/sub-scopeoctylFractal
08/26/2019, 6:45 PMsam
08/26/2019, 6:46 PMoctylFractal
08/26/2019, 6:47 PMsuspend fun CoroutineScope.foo()
, I was talking about context, because suspend
functions have coroutineContext
, as does the scope.suspend fun CoroutineScope...
, but that's not recommended because 1) it's got two different contexts and 2) it doesn't fit with the structured concurrency modelsam
08/26/2019, 6:48 PMwithoutclass
08/26/2019, 6:50 PMoctylFractal
08/26/2019, 6:52 PMwithoutclass
08/26/2019, 6:54 PMoctylFractal
08/26/2019, 6:57 PMCoroutineScope
extension, it should return some form of `Job`/`Channel`/etc., something that can cancel all coroutines started from that function. If you're returning that, you've already opened a new scope (with launch
, async
, produce
, etc.) to call suspend functions in, and don't need the suspend
modifier for any of it. The only time I could see use for it is when you want to keep the same thread for some other suspend function you call outside of what you use the scope for, but that's extremely niche.withoutclass
08/26/2019, 7:10 PMlaunch
,async
, and produce
are coroutine builders, they don't create new scopes.