I’m curious if it’s possible to create something i...
# announcements
n
I’m curious if it’s possible to create something in Kotlin where a stream of values is emitted only when one is requested. So something like
iterator { produceValue() }
where produceValue is called each time the consumer calls
next()
r
I think
generateSequence
matches what you want? Or
sequence
if it's more complicated for example
generateSequence(0) { it + 1 }
gives you sequence of
0, 1, 2, ...
till you are calling
next()
/ iterating
n
Potentially, yeah. Seems like https://kotlinlang.org/docs/sequences.html#from-chunks describes what I’m trying to do — “[yield()] return[s] an element to the sequence consumer and suspend the execution of sequence() until the next element is requested”
r
ye, if it's more complicated, you can use
sequence
to make iterable from function that suspends execution until next element needs more execution if you can simply make a function
produceNextValue(currentValue)
then
generateSequence
is enough for you