Skip to content

Instantly share code, notes, and snippets.

@robertoestivill
Last active May 24, 2018 12:11
Show Gist options
  • Save robertoestivill/92328728ec4e322476ee6089d9a1c7fb to your computer and use it in GitHub Desktop.
Save robertoestivill/92328728ec4e322476ee6089d9a1c7fb to your computer and use it in GitHub Desktop.
Kotlin ReceiverChannel example with background and "UI" threads.
package testkotlin
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.channels.produce
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import kotlinx.coroutines.experimental.newSingleThreadContext
import kotlinx.coroutines.experimental.runBlocking
import kotlinx.coroutines.experimental.withContext
import kotlin.coroutines.experimental.CoroutineContext
val bgContext = newFixedThreadPoolContext(4, "BG")
val uiContext = newSingleThreadContext("UI")
fun main(args: Array<String>): Unit = runBlocking {
val squares = produceSquares(bgContext)
squares.consumeEach {
withContext(uiContext) {
println("[${Thread.currentThread().name}] - Consumed: $it")
}
}
}
fun produceSquares(context: CoroutineContext): ReceiveChannel<Int> = produce(context) {
for (x in 1..5) {
val y = x * x
println("[${Thread.currentThread().name}] - Produced: $y")
send(y)
}
}
[BG-2] - Produced: 1
[BG-2] - Produced: 4
[UI] - Consumed: 1
[BG-2] - Produced: 9
[UI] - Consumed: 4
[BG-3] - Produced: 16
[UI] - Consumed: 9
[BG-4] - Produced: 25
[UI] - Consumed: 16
[UI] - Consumed: 25
Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment