The implementation of a Fibonacci sequence using a producer is actually quite similar to the ones for iterators and sequences. You only need to replace yield() with send():
val context = newSingleThreadContext("myThread")
val fibonacci = produce(context) {
send(1L)
var current = 1L
var next = 1L
while (true) {
send(next)
val tmpNext = current + next
current = next
next = tmpNext
}
}
fun main(args: Array<String>) = runBlocking {
fibonacci.take(10).consumeEach {
println(it)
}
}
The previous example will print the first ten numbers produced: