https://kotlinlang.org logo
Title
l

Luis Munoz

05/19/2020, 8:42 PM
How do I implement two way generator with kotlin coroutines? For example in javascript you would do:
function* generatorFunction(i) {
   yield i
   yield i +1
}

let gen = generator(5)
gen.next() //  value=5, done=false
gen.next() //  value=6, done=false
// WHAT I WANT IS THIS
gen.next(100) // <-- here I pass value and get back another value at next yield point
so in generator it would be let x = yield i to get the input value
l

Luis Munoz

05/19/2020, 8:48 PM
thank you
generate<String, ByteBuffer> { val result = parse() // ERROR // Doesn't let me call suspend function something about // @RestrictsSuspension yield(result) }
@octylFractal do you how I can call other suspend functions inside the generate?
o

octylFractal

05/19/2020, 9:42 PM
yes, this is restricted like a
sequence
because there's no scope
l

Luis Munoz

05/19/2020, 9:43 PM
so I can't call another suspend function?
o

octylFractal

05/19/2020, 9:43 PM
I don't really have a fix for it, you'd have to introduce something more Flow-like
l

Luis Munoz

05/19/2020, 9:43 PM
or can I extend
a

araqnid

05/19/2020, 9:44 PM
you can call another suspend function only if it is defined as an extension of GeneratorBuilder — i.e. that will only suspend on
yield
l

Luis Munoz

05/19/2020, 9:51 PM
changing methods to suspend fun GeneratorBuilder<String, ByteBuffer>.parse() seems to work, thanks @araqnid