【发布时间】:2020-04-09 18:01:44
【问题描述】:
更新: 如果我先执行一个没有超时的协程,然后再执行一个超时,它就可以工作。但是如果我先执行一个带有Timeout的协程,那么它会给我一个错误。异步也是如此。
我正在创建一个演示 kotlin 多平台应用程序,其中我正在使用 ktor 执行 API 调用。 我想在 ktor 请求上有一个可配置的超时功能,所以我在协程级别使用 withTimeout。
这是我使用网络 API 调用的函数。
suspend fun <T> onNetworkWithTimeOut(
url: String,
timeoutInMillis: Long,
block: suspend CoroutineScope.() -> Any): T {
return withTimeout(timeoutInMillis) {
withContext(dispatchers.io, block)
} as T
}
suspend fun <T> onNetworkWithoutTimeOut(url: String, block: suspend CoroutineScope.() -> Any): T {
return withContext(dispatchers.io, block) as T
}
这是我的 iOSMain 模块的 AppDispatcher 类。
@InternalCoroutinesApi
actual class AppDispatchersImpl : AppDispatchers {
@SharedImmutable
override val main: CoroutineDispatcher =
NsQueueDispatcher(dispatch_get_main_queue())
@SharedImmutable
override val io: CoroutineDispatcher =
NsQueueDispatcher(dispatch_get_main_queue())
internal class NsQueueDispatcher(
@SharedImmutable private val dispatchQueue: dispatch_queue_t
) : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
NSRunLoop.mainRunLoop().performBlock {
block.run()
}
}
}
}
所以带有超时的函数在 iOS 客户端中给了我以下错误。
kotlin.IllegalStateException: There is no event loop. Use runBlocking { ... } to start one.
我正在使用 kotlin-coroutine-native 的 1.3.2-native-mt-1 版本。 我在以下 URL 创建了一个示例演示应用程序。 https://github.com/dudhatparesh/kotlin-multiplat-platform-example
【问题讨论】:
-
错误只出现在iOS客户端?安卓客户端正常吗?
-
是的,Android 客户端运行良好
-
在尝试更新 github.com/joreilly/PeopleInSpace 以使用本机 mt 版本的协程时遇到类似问题....尝试在 github.com/Kotlin/kotlinx.coroutines/issues/462 中提到的
1.3.3-native-mt版本。似乎我们应该使用newSingleThreadContext,但由于某种原因无法解决。
标签: ios kotlin kotlin-coroutines ktor kotlin-native