Yielding values

As mentioned previously, yielding a value will result in the suspension of the sequence or iterator until a value is requested from it again. A simple example of this can be seen here:

val iterator = buildIterator {
yield("First")
yield("Second")
yield("Third")
}

This code will build an iterator that contains three elements. The first time an element is requested, the first line will be executed, yielding the value "First" and suspending execution afterwards.

When the next element is requested, the second line will be executed, yielding "Second" and suspending again. Therefore, to be able to obtain the three elements that this iterator contains, it's simply necessary to call the next() functions three times:


fun main(args: Array<String>) {
val iterator = buildIterator {
yield("First")
yield("Second")
yield("Third")
}

println(iterator.next())
println(iterator.next())
println(iterator.next())
}

In this example, the iterator was suspended three times, each time after a value was yielded:

As pointed out previously, because they can't suspend during their execution, suspending sequences and iterators can be called from non-suspendable code. Notice how in this case next() is being called from main directly, with no coroutine builder being involved.
..................Content has been hidden....................

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