Skip to content

Instantly share code, notes, and snippets.

@alexrios
Created January 12, 2020 21:05
Show Gist options
  • Save alexrios/0136e3b27357447f1e644d9366c35a96 to your computer and use it in GitHub Desktop.
Save alexrios/0136e3b27357447f1e644d9366c35a96 to your computer and use it in GitHub Desktop.
Using pipeline pattern with Kotlin channels
package app
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
sq(gen(listOf(1, 2, 3, 4, 5))).consumeEach { println(it) }
}
private fun CoroutineScope.gen(nums: List<Int>): Channel<Int> {
val out = Channel<Int>()
launch {
nums.forEach { out.send(it) }
out.close()
}
return out
}
private fun CoroutineScope.sq(input: Channel<Int>): Channel<Int> {
val out = Channel<Int>()
launch {
input.consumeEach { out.send(it * it) }
out.close()
}
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment