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

dave08

10/25/2018, 5:43 PM
I have a setup like this (just made it much simpler...), but it hangs... I tried different types of channels... conflated and all, how could I get this to work?
Copy code
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.actor
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.runBlocking
import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) = runBlocking {
	val progressNotifier = actor<Long>(<http://Dispatchers.IO|Dispatchers.IO>) {
		consumeEach {
			println(it.toString())
		}
	}

	val progressMapper = actor<Int>(<http://Dispatchers.IO|Dispatchers.IO>) {
		for (it in channel) {
			progressNotifier.offer(it.toLong())
		}
	}

	(0..5).forEach {
		progressMapper.offer(it)
	}

	progressMapper.close()
}
a

Alexander

10/25/2018, 5:58 PM
Your first actor is never finished
d

dave08

10/25/2018, 5:59 PM
When I use consumeEach, and close the second one, should the first one finish?
This doesn't print anything:
Copy code
fun main(args: Array<String>) = runBlocking {
    println("set up #1")
	val progressNotifier = actor<Long>(<http://Dispatchers.IO|Dispatchers.IO>, Channel.CONFLATED) {
		consumeEach {
			println(it.toString())
		}
	}

    println("set up #2")
	val progressMapper = actor<Int>(<http://Dispatchers.IO|Dispatchers.IO>, Channel.CONFLATED) {
		consumeEach {
			progressNotifier.offer(it.toLong())
		}
	}

	(0..5).forEach {
        println("sending $it")
		progressMapper.offer(it)
	}

	progressMapper.close()
}
a

Alexander

10/25/2018, 6:03 PM
Closing a channel implemented via sending a special message to it. So you should explicitly call close
d

dave08

10/25/2018, 6:04 PM
Ok that did it, thanks!
2 Views