Suspending a Fibonacci sequence using a producer

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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.160