Created
January 9, 2019 15:59
-
-
Save smitsgit/89eb1b06f99017243b134b5e3dbb2d2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package generator | |
import kotlin.coroutines.* | |
import kotlin.coroutines.intrinsics.* | |
fun kotlincoro() = generate<String, String>{ | |
println("[ coroutine ]: started") | |
println("[ coroutine ]: suspended at first yield and sent data to main") | |
val coroData = yield("Hello") // yield() causes coroutine to produce value "Hello" for consumer | |
// and kotlincoro function gets suspended till consumer invokes | |
// and gets it out of suspension | |
println("[ coroutine ]: resumed from first yield") | |
println("[ coroutine ]: received { $coroData }") | |
println("[ coroutine ]: reached and suspended at 2nd yield and sent data to main") | |
val coroNewData = yield("Bye")// yield() causes coroutine to produce value "Bye" for consumer | |
// and kotlincoro gets suspended till consumer invokes | |
// and gets it out of suspension | |
println("[ coroutine ]: resumed from second yield") | |
println("[ coroutine ]: received { $coroNewData }") | |
println("[ coroutine ]: ended") | |
} | |
fun main(args: Array<String>) { | |
val g = kotlincoro() // This will put the generator into created state | |
// We send empty string to g.next() to get the generator into suspended state | |
// cause there is no point in sending any value in g.next("") till the generator is started and suspended | |
val initData = g.next("") // Will make gen advance till first yield and if there is data, that will be given to consumer | |
println("[ In main ]: { $initData }") | |
println("==============================") | |
val data = g.next("whats up") // Will make gen advance till second yield and if there is data, that will be given to consumer | |
println("[ In main ]: { $data }") | |
println("==============================") | |
g.next("Howdy there ?") | |
println("[In main ] : again") | |
g.next("") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment