Home > OS >  How to define a task, run it in the future, and cancel it using Kotlin coroutines
How to define a task, run it in the future, and cancel it using Kotlin coroutines

Time:01-21

I'm new to kotlin Coroutines. I define a Runnable and call it asynchronously in a function using Handler with a delay. The important thing is that the previous task must be canceled before each call so that it is not performed after the delay. This is my code using Handler and Runnable. How can I do this with Kotlin Coroutines?

val runnable = java.lang.Runnable {
    ....
}

val handler = Handler()

private fun myFunction() {
      handler.removeCallbacks(runnable)// This is important
      handler.postDelayed(runnable, 3000)
 }

CodePudding user response:

You can define a Job and cancel it:

private var job: Job? = null

private fun myFunction() {
  job?.cancel()
  job = scope.launch(ioDispatcher) {
            delay(3000)
            ...
        }
}
  •  Tags:  
  • Related