How do I print all the handler names with below pr...
# coroutines
s
How do I print all the handler names with below program? Currently, it's only printing 0th handler name and waiting for it to finish:
Copy code
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.util.stream.IntStream

fun main() {
    runBlocking {
        val asyncs = IntStream.range(0, 6).mapToObj {
            GlobalScope.async {
                handleData("handler-$it")
            }
        }
        asyncs.forEach {
            runBlocking {
                it.await()
            }
        }
    }
}

private fun handleData(handlerName: String) {
    println(handlerName)
    while (true) {
    }
}
Current output: handler-0 Expected output: handler-0 handler-1 handler-2 handler-3 handler-4 handler-5
a
Do you mean something like this?
Copy code
fun main() {
    runBlocking {
        val asyncs = IntStream.range(0, 6).mapToObj {
            GlobalScope.async {
                handleData("handler-$it")
            }
        }.toList()
        asyncs.awaitAll()
    }
}
👍 2
💯 2
s
Ahh.. I missed out on collecting via toList. Thought it works like map and automatically collects to list. Thanks for the quick help. 🙂
k
The issue here was the fact that the runBlocking inside the forEach would never finish, which is why the stream never processed the next item.