withTimeout 函数给出了 IllegalStateException:没有事件循环。使用 runBlocking { ... } 启动一个。在 Kotlin 多平台 iOS 客户端中

Par*_*hat 18 ios kotlin ktor kotlin-native kotlin-coroutines

更新:如果我首先在没有超时的情况下执行协程然后使用超时,它会起作用。但是如果我先执行一个协程 withTimeout 那么它会给我一个错误。异步也是如此。

我正在创建一个演示 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
}
Run Code Online (Sandbox Code Playgroud)

这是我的 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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

所以带有超时的函数在 iOS 客户端中给了我以下错误。

kotlin.IllegalStateException: There is no event loop. Use runBlocking { ... } to start one.
Run Code Online (Sandbox Code Playgroud)

我正在使用 kotlin-coroutine-native 的 1.3.2-native-mt-1 版本。我在以下 URL 创建了一个示例演示应用程序。 https://github.com/dudhatparesh/kotlin-multiplat-platform-example

Joh*_*lly 9

所以,正如上面评论中提到的,我有类似的问题,但结果是native-mt由于其他库中的传递依赖关系,它没有选择版本。添加了以下内容,现在正在解决。

        implementation('org.jetbrains.kotlinx:kotlinx-coroutines-core-native') 
        {
            version {
                strictly '1.3.3-native-mt'
            }
        }
Run Code Online (Sandbox Code Playgroud)

另请注意https://github.com/Kotlin/kotlinx.coroutines/blob/native-mt/kotlin-native-sharing.md 中的指导

开始在https://github.com/joreilly/PeopleInSpace 中使用它