Predict the output
Two workers receive from the same channel. How many lines are printed in total?
fun main() = runBlocking {
val jobs = Channel<Int>()
repeat(2) { worker ->
launch { for (j in jobs) println("w$worker got $j") }
}
for (i in 1..4) jobs.send(i)
jobs.close()
}Hint 1 of 1
Can two receivers get the same element?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 4: each job goes to one worker
Correct. A channel element is received by exactly one receiver.
Why not the others?
- B 8: both workers get every job. That's SharedFlow behaviour, not a channel's.
- C 2: each worker takes one job and stops. for (j in jobs) loops until the channel is closed.
- D 0: send suspends forever. Workers are receiving, so each rendezvous send completes.