Search code examples
androidkotlinkotlin-multiplatform

Execute code after 2 seconds in pure Kotlin


I need to execute some code after two seconds of waiting (without blocking the UI thread). The problem is that this is usually resolved with Timer or Handler but my app is using Kotlin Multiplatform, so I need it to be just pure Kotlin, not any Java library.

I would also need to be able to cancel the timer if I want to.

I have seen this answer asking more or less the same but they solve it using:

runBlocking {
    println("Wait for 5sec")
    delay(5000)
    println("Done waiting for 5sec")
}

But I don't really know how to cancel it and also if this is blocking the rest of the app.


Solution

  • You could get a Job reference when launching coroutine. You could do something like this:

        val job = coroutineScope.launch {
            delay(1000)
            doYourStuff()
        }
    

    After thay you can use job.cancel(), or what ever you need. Also, you can define coroutine scope like this.

    CoroutineScope(Dispatchers.Main)
    

    Or any other dispatcher that suits your needs. Good luck.