Search code examples
ioskotlinkotlin-coroutineskotlin-multiplatformkmm

Kotlin coroutines delay do not work on IOS queue dispatcher


I have a KMM app, and there is code:

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) }
            }
        }
    }

And if I replace withContext(Dispatchers.Default) { delay(DELAY_TIME) } with delay(DELAY_TIME) execution is never returned to while cycle and it will have only one iteration.

And ApplicationDispatcher for IOS looks like:

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()
        }
    }
}

And from delay source code I can guess, that DefaultDelay should be returned and there is should be similar behaviour with/without withContext(Dispatchers.Default)

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

Thanks!

P.S. I got ApplicationDispatcher from ktor-samples.


Solution

  • Probably ApplicationDispatcher is some old stuff, you don't need to use it anymore:

    CoroutineScope(Dispatchers.Default).launch {
    
    }
    

    or

    MainScope().launch {
    
    }
    

    And don't forget to use -native-mt version of coroutines, more info in this issue