Suspending sequences are quite different from suspending iterators, so let's take a look at some of the characteristics of suspending sequences:
- They can retrieve a value by index
- They are stateless, and they reset automatically after being interacted with
- You can take a group of values with a single call
In order to create a suspending sequence, we will use the builder buildSequence(). This builder takes a suspending lambda and returns a Sequence<T>, where T can be inferred by the elements that are yielded, as for example the following:
val sequence = buildSequence {
yield(1)
}
This will make the sequence a Sequence<Int>. But, similar to iterators, you can always specify a T as long as the values that are yielded are compliant:
val sequence: Sequence<Any> = buildSequence {...
yield("A")
yield(1)
yield(32L)
}