【发布时间】:2018-09-18 19:16:51
【问题描述】:
有没有办法编写下面的 Kotlin 代码,以便它在 JVM 和 JavaScript 上以相同的方式编译和工作?
fun <A: Any> request(request: Any): A = runBlocking {
suspendCoroutine<A> { cont ->
val subscriber = { response: A ->
cont.resume(response)
}
sendAsync(request, subscriber)
}
}
fun <Q : Any, A : Any> sendAsync(request: Q, handler: (A) -> Unit) {
// request is sent to a remote service,
// when the result is available it is passed to handler(... /* result */)
}
当编译为 JVM 时,代码可以编译并正常工作。 由于不存在函数 runBlocking,在针对 JavaScript 时会发出编译错误
【问题讨论】:
标签: kotlin kotlin-coroutines kotlin-js