aus*_*ser 5 kotlin kotlin-js kotlin-coroutines
有没有办法编写下面的 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 */)
}
Run Code Online (Sandbox Code Playgroud)
当针对 JVM 进行编译时,代码可以编译并正常工作。由于不存在函数 runBlocking,在针对 JavaScript 时会发出编译错误
你的主要问题是你没有要求你真正需要的东西。您编写的代码启动一个协程,将其挂起,然后阻塞直到完成。这完全相当于根本没有协程而只是发出阻塞网络请求,这是您不可能指望 JavaScript 允许的事情。
您实际上要做的就是退回到 的调用站点request()
并将其包装在launch
:
GlobalScope.launch(Dispatchers.Default) {
val result: A = request(...)
// work with the result
}
Run Code Online (Sandbox Code Playgroud)
完成此操作后,您可以将请求函数重写为
suspend fun <A: Any> request(request: Any): A = suspendCancellableCoroutine {
sendAsync(request, it::resume)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2598 次 |
最近记录: |