Andrea Giuliano
08/26/2020, 7:57 AMsuspend fun myFun() = coroutineScope {}
I wonder, given that a suspending function must be called within a scope, what’s the point of creating a new scope like in there?octylFractal
08/26/2020, 7:58 AMAndrea Giuliano
08/26/2020, 8:01 AMsuspend fun myFun() = coroutineScope {
launch { timeExpensiveFun() }
}
and
suspend fun myFun() =
launch { timeExpensiveFun() }
the second function will return while launch will still be in progress, while in the first case myFun will wait for launch to be completed. Is that right?
If this is the case would it be right to say that in my code I can use coroutineScope {} when I need to bridge sync and async world instead of runBlocking{} ?octylFractal
08/26/2020, 8:02 AMAndrea Giuliano
08/26/2020, 8:03 AMoctylFractal
08/26/2020, 8:03 AMlaunch
is defined as an extension of CoroutineScope
, i.e. fun CoroutineScope.launch
CoroutineScope
(at least in the example) and therefore will result in a compile error
(the first one has it implicitly as this
from coroutineScope {}
)Andrea Giuliano
08/26/2020, 8:05 AMsuspend fun myFun() =
scope.launch { timeExpensiveFun() }
octylFractal
08/26/2020, 8:05 AMcoroutineScope
to bridge sync and async as it itself is suspend
, but runBlocking
already provides you with a CoroutineScope
inside it just like coroutineScope
suspend
)
this is discouraged unless you really mean to do it though, structured concurrency is preferred when possibleAndrea Giuliano
08/26/2020, 8:06 AMoctylFractal
08/26/2020, 8:08 AMsuspend
functionsAndrea Giuliano
08/26/2020, 8:52 AMfun callAllGuys() {
private val scope = CoroutineScope(Executors.newFixedThreadPool(2).asCoroutineDispatcher())
for (website in websites) {
scope.launch(callWebsiteLambda())
}
}
or do you think that’s wrong and there is a better example with structured concurrency?Zach Klippenstein (he/him) [MOD]
08/26/2020, 9:24 AMclass YourApiWrapper {
private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
fun callAllApis() {
for (website in websites) {
scope.launch { … }
}
}
fun shutdown () {
scope.cancel()
}
}