https://kotlinlang.org logo
#getting-started
Title
# getting-started
o

Oleg Shuliak

10/11/2022, 2:27 PM
good day everyone. got a coroutine question. I want to set the property value for each object in the list by calling the suspension function and setting the result:
Copy code
coroutineScope {
            workflows.forEach {
                it.status = formWorkflowActivationStateManager.getCurrentState(it, companyId).toWorkflowStatus()
            }
        }
I’m wondering if the
coroutineScope
is enough to parallel those executions or if I need to use
async/await
?
s

Sam

10/11/2022, 2:29 PM
Yes, you need to use
async
— coroutines are sequential by default
o

Oleg Shuliak

10/11/2022, 2:58 PM
thanks @Sam but could you give me a hint on how to implement that for each entity in a list?
s

Sam

10/11/2022, 3:01 PM
Wrong Sam 😉
👋 1
s

Sam

10/11/2022, 3:01 PM
In your example, since you don’t need to return a result from the parallel tasks, you can just use
launch
, like:
Copy code
coroutineScope {
    workflows.forEach {
        launch { it.status = ... }
    }
}
The
coroutineScope
will wait for all the launched tasks to finish before returning.
👍 2
o

Oleg Shuliak

10/11/2022, 3:02 PM
sorry @Sam my bad 😄
💖 1
and
launch
will create a parallel task for each entity, right?
s

Sam

10/11/2022, 3:11 PM
Yes 👍
y

Youssef Shoaib [MOD]

10/11/2022, 3:14 PM
Indeed it will. The equivalent if you wanted a result out of each would be to do
Copy code
coroutineScope {
  workflows.map { async { it.status = ... } }.awaitAll()
}
Keep in mind that this and
launch
will cancel all operations eventually if one fails. If that's not what you want, you can do
supervisorScope
instead of
coroutineScope
o

Oleg Shuliak

10/11/2022, 3:17 PM
prefect, thanks everyone for help!
3 Views