Last active
January 22, 2018 19:14
-
-
Save dkandalov/d39bca4aca1dce9e709c541aa6eb3f52 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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