Kotlin Defer Code Execution (KDCE)

There are several ways to do this;

1. Using Handler

Handler().postDelayed({
    TODO("Do something")
    }, 2000)

2. Using the Timer

Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
    }
}, 2000)

// Shorter

Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)


// Shortest

Timer().schedule(2000) {
    TODO("Do something")
}

3. Using Executors

Executors.newSingleThreadScheduledExecutor().schedule({
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

4. Using Coroutines

 GlobalScope.launch {
   delay(1000)
   yourFn()
 }

5. Using ViewModel Scope

myViewModel.viewModelScope.launch {
        delay(2000)
        // DoSomething()
    }

Done.


Post a Comment

Previous Next

نموذج الاتصال