1

我有一个 KMM 应用程序,并且有代码:

fun getWeather(callback: (WeatherInfo) -> Unit) {
        println("Start loading")
        GlobalScope.launch(ApplicationDispatcher) {
            while (true) {
                val response = httpClient.get<String>(API_URL) {
                    url.parameters.apply {
                        set("q", "Moscow")
                        set("units", "metric")
                        set("appid", weatherApiKey())
                    }
                    println(url.build())
                }
                val result = Json {
                    ignoreUnknownKeys = true
                }.decodeFromString<WeatherApiResponse>(response).main
                callback(result)

                // because ApplicationDispatcher on IOS do not support delay
                withContext(Dispatchers.Default) { delay(DELAY_TIME) }
            }
        }
    }

如果我withContext(Dispatchers.Default) { delay(DELAY_TIME) }delay(DELAY_TIME)执行替换,则永远不会返回到 while 循环,它只会有一次迭代。

ApplicationDispatcher对于 IOS 看起来像:

internal actual val ApplicationDispatcher: CoroutineDispatcher = NsQueueDispatcher(dispatch_get_main_queue())

internal class NsQueueDispatcher(
    private val dispatchQueue: dispatch_queue_t
) : CoroutineDispatcher() {
    override fun dispatch(context: CoroutineContext, block: Runnable) {
        dispatch_async(dispatchQueue) {
            block.run()
        }
    }
}

delay源代码中我可以猜到,DefaultDelay应该返回并且应该有类似的行为有/没有withContext(Dispatchers.Default)

/** Returns [Delay] implementation of the given context */
internal val CoroutineContext.delay: Delay get() = get(ContinuationInterceptor) as? Delay ?: DefaultDelay

谢谢!

PS 我ApplicationDispatcherktor-samples得到的。

4

1 回答 1

1

可能ApplicationDispatcher是一些旧的东西,你不需要再使用它了:

CoroutineScope(Dispatchers.Default).launch {

}

或者

MainScope().launch {

}

并且不要忘记使用-native-mt协程的版本,更多信息在这个问题上

于 2021-03-30T07:51:17.533 回答