Last active
November 23, 2022 10:59
-
-
Save ichenhe/e2e7156defd25eef4378fa265d3224a2 to your computer and use it in GitHub Desktop.
Using Kotlin to implemant Promise (js) style coroutine. 用 Kotlin 实现 Promise (js) 风格的协程 API
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
import kotlin.concurrent.thread | |
import kotlin.coroutines.* | |
typealias Callback<T> = (T) -> Unit | |
class Promise<T>(private val run: (Callback<T>) -> Unit) { | |
fun then(callback: Callback<T>) { | |
run(callback) | |
} | |
} | |
fun heavyJob(): Promise<String> { | |
return Promise { callback -> | |
thread { | |
Thread.sleep(2000) | |
callback("slow") | |
} | |
} | |
} | |
@RestrictsSuspension | |
interface AsyncScope { | |
suspend fun <T> await(block: () -> Promise<T>): T | |
} | |
fun async(block: suspend AsyncScope.() -> Unit) { | |
val completion = Async() | |
block.startCoroutine(completion, completion) | |
} | |
class Async : Continuation<Unit>, AsyncScope { | |
override val context: CoroutineContext | |
get() = EmptyCoroutineContext | |
override fun resumeWith(result: Result<Unit>) { | |
result.getOrThrow() | |
} | |
override suspend fun <T> await(block: () -> Promise<T>): T = suspendCoroutine { continuation -> | |
block().then { result -> | |
continuation.resume(result) | |
} | |
} | |
} | |
fun asyncCall() { | |
async { | |
val r = await { heavyJob() } | |
println(r) | |
} | |
} | |
fun main() { | |
asyncCall() | |
println("first") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://chenhe.me/post/dive-into-kotlin-coroutines-2