Hadi Tok
10/07/2018, 2:04 PMprint(5)
to run. how should I go for doing this? the current code I sent runs the coroutines in loop parallel but print(5)
does not wait for completion of the others.Dominaezzz
10/07/2018, 2:09 PMforEach
call inside a coroutineScope
call.Dominaezzz
10/07/2018, 2:13 PMforEach
to map
. Then call forEach { it.join() }
.Hadi Tok
10/07/2018, 2:18 PMDaniel Tam
10/07/2018, 2:49 PMjoin
is very explicit about what you're doing, rather than implicitly waiting for the scope to finishDico
10/07/2018, 3:31 PMcoroutineScope
should be considered as the idiomatic approachHadi Tok
10/07/2018, 3:51 PMjoin()
is called. also it is not clear that the code is doing a parallel work. using coroutineScope
gives more visibility to parallel execution.Dico
10/07/2018, 3:52 PMlaunch
Hadi Tok
10/07/2018, 4:06 PMgildor
10/07/2018, 9:57 PMlistOf(1,2,3).map { launch {} }.joinAll()
Dico
10/07/2018, 10:03 PMjoinAll()
gildor
10/07/2018, 10:13 PMDominaezzz
10/07/2018, 10:27 PMjoinAll
is like conditional goto and coroutineScope
is like if/else. More "structure".gildor
10/08/2018, 1:13 AMgoto
and joinAll
For me joinAll looks much more explicit just because you explicitly says that you want to wait all jobs in list, very clear. In case of coroutineScope it’s implementation detail that changed one version ago.Daniel Tam
10/08/2018, 5:19 AMjoin
and joinAll
makes it very clear what you're trying to do.Hadi Tok
10/08/2018, 7:46 AM@Test
fun testCoroutineOrder() = runBlocking {
listOf(1, 2, 3, 4).forEach {
launch {
delay(1000)
println(it)
}.join()
}
print(5)
}
and
@Test
fun testCoroutineOrder2() = runBlocking {
listOf(1, 2, 3, 4).map {
launch {
delay(1000)
println(it)
}
}.forEach { it.join() }
print(5)
}
first executes them in order but second executes them asynchronously. but joinAll
changes the game. Probably doing the same thing as forEach{ it.join() }
but since it is applied to the list as whole It makes more sense in the first look.Hadi Tok
10/08/2018, 7:52 AMcoroutineScope
(even supervisorScope
) still needs to be kept in mind. if the coroutines are not in a list like
coroutineScope{
getA()
getB()
getC()
}