poohbar
10/09/2018, 6:46 PMparallelStream equivalent in kotlin.. does this make sense?
runBlocking {
myItems.map {
GlobalScope.launch {
// do something
}
}.forEach { it.join() }
}
// now do something with all itemsenleur
10/09/2018, 6:51 PMpoohbar
10/09/2018, 6:53 PMnwh
10/09/2018, 7:01 PMGlobalScope#launch uses the default dispatcher (common pool)enleur
10/09/2018, 7:01 PMgildor
10/10/2018, 12:57 AMgildor
10/10/2018, 1:01 AMZach Klippenstein (he/him) [MOD]
10/10/2018, 3:22 PMGlobalScope.
runBlocking {
myItems.forEach {
launch(Dispatchers.Default) {
// Do something.
println("Processing $it…")
Thread.sleep(it * 1000L)
println("$it finished.")
}
}
}
println("All done.")
Prints:
Processing 1…
Processing 2…
Processing 3…
1 finished.
2 finished.
3 finished.
All done.
(For actually blocking work though, you should use <http://Dispatchers.IO|Dispatchers.IO> not Dispatchers.Default).gildor
10/10/2018, 3:42 PMjoinAll()Zach Klippenstein (he/him) [MOD]
10/10/2018, 4:15 PMZach Klippenstein (he/him) [MOD]
10/10/2018, 4:16 PMGlobalScope should be used very rarely, and so doing the “right thing” here and using the parent scope to launch children makes the `join`s redundant. If the example was using async then yes you’d need some processing at the end, but since it’s using launch it looks like the intention of this code is just to not leave the runBlocking coroutine until all the child work is done, which is why structured concurrency was introduced in the first place. I would expect this sort of pattern will get more common and start to look less suspicious over time