Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Last active January 22, 2018 19:14
Show Gist options
  • Select an option

  • Save dkandalov/d39bca4aca1dce9e709c541aa6eb3f52 to your computer and use it in GitHub Desktop.

Select an option

Save dkandalov/d39bca4aca1dce9e709c541aa6eb3f52 to your computer and use it in GitHub Desktop.
fun main(args: Array<String>) {
val f = create {
println(1)
yield() // 1
println(2)
yield() // 2
println(3)
}
f.resume() // starts "f"
f.resume() // continues from "yield 1"
f.resume() // continues from "yield 2"
f.resume() // continues from "yield 2" (again)
}
class YieldingFunction {
private var c: Continuation<Unit>? = null
fun resume() {
c?.resume(Unit)
}
suspend fun yield() {
suspendCoroutineOrReturn { it: Continuation<Unit> ->
c = it
COROUTINE_SUSPENDED
}
}
companion object {
fun create(block: suspend YieldingFunction.() -> Unit): YieldingFunction {
val continuation = MyContinuation()
return YieldingFunction().apply {
c = block.createCoroutineUnchecked(this, continuation)
}
}
}
}
class MyContinuation: Continuation<Unit> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resume(value: Unit) {}
override fun resumeWithException(exception: Throwable) = throw exception
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment