https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sanket Mehta

02/19/2020, 2:45 PM
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

Andrzej

02/19/2020, 3:05 PM
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

Sanket Mehta

02/19/2020, 4:17 PM
Ahh.. I missed out on collecting via toList. Thought it works like map and automatically collects to list. Thanks for the quick help. 🙂
k

Kroppeb

02/19/2020, 5:03 PM
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.
5 Views