sean
08/21/2020, 1:03 AMsuspend fun doSomeWork(): Thing = supervisorScope {
val foo = async {
val result = async {
fetchResultFromNetwork()
}
val otherResult = async {
fetchOtherResultFromNetwork()
}
result.await() + otherResult.await()
}
val bar = async {
anotherThing()
}
Thing(foo.await(), bar.await())
}
Would you go with:
a) suspend fun + scope builder
suspend fun doSomeWork(): Thing = supervisorScope {
val foo = async {
fetchAndMergeResults()
}
val bar = async {
anotherThing()
}
Thing(foo.await(), bar.await())
}
suspend fun fetchAndMergeResults = coroutineScope {
val result = async {
fetchResultFromNetwork()
}
val otherResult = async {
fetchOtherResultFromNetwork()
}
result.await() + otherResult.await()
}
b) Extension on CoroutineScope which returns a Deferred
suspend fun doSomeWork(): Thing = supervisorScope {
val foo = foo()
val bar = async {
anotherThing()
}
Thing(foo.await(), bar.await())
}
fun CoroutineScope.foo(): Deferred<Foo> {
async {
val result = async {
fetchResultFromNetwork()
}
val otherResult = async {
fetchOtherResultFromNetwork()
}
result.await() + otherResult.await()
}
}
c) Something else?
Any thoughts on what's preferred between the first two options? I'm aware of the conventions on suspend fun vs extension on CoroutineScope described in this video: and this blog post: https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055 and I think both the examples above follow the convention, but I'm not sure if one is preferred in this case for one reason or another. Any opinions would be appreciated!gildor
08/21/2020, 1:57 AMsean
08/21/2020, 3:26 AMgildor
08/21/2020, 8:14 AMasync {}
so no reason to provide deferred
It’s in general easier to read code and less chance to forgot call .await()async
you need scope, so you should somehow pass it (to keep structure concurrence). suspend function doesn’t require any scope, you can call it from any suspend lambdasean
08/21/2020, 4:35 PMgildor
08/22/2020, 11:08 AMbut by the time you have a suspend lambda you'll already be in a scopeBut it's not true for usual suspend functions, only for coroutine builders Also it's not an issue of scope creation, but the fact that you always need additional argument for scope (or receiver), it becomes an issue if your want to use it for extension function