1

I am new in coroutines. So now I look how to use coroutines instead of handlers

The Handler code:

fun Handler.repostDelayed(func: Runnable, delay: Long) {
removeCallbacksAndMessages(null)
postDelayed(func, delay)
}

Analog in Coroutines

inline fun AppCompatActivity.repostDelayed(crossinline func: () -> Unit, delay: Long) {
    lifecycleScope.cancel()
    lifecycleScope.launch {
        delay(delay)  //debounce timeOut
        func()
    }
}

But it does not work. Could You fix my expression for Coroutines, please?

Serg Burlaka
  • 2,351
  • 24
  • 35
  • You can't just cancel the coroutine scope and then hope to keep using it. You could fix it by cancelling the particular job instead, but it would still be racy code. – Marko Topolnik Feb 21 '20 at 12:53

1 Answers1

1

So, I have found the solution here. And have just modified a little:

 fun <T, V> CoroutineScope.debounce(
    waitMs: Long = 300L,
    destinationFunction: T.(V) -> Unit
): T.(V) -> Unit {
    var debounceJob: Job? = null
    return { param: V ->
        debounceJob?.cancel()
        debounceJob = launch {
            delay(waitMs)
            destinationFunction(param)
        }
    }
}

usage:

 private val delayFun: String.(Boolean) -> Unit = lifecycleScope.debounce(START_DELAY) {
        if(it){
            print(this)
        }
    }

     //call function
     "Hello world!".delayFun(true)

The benefit of coroutine usage is you don't need to cancel coroutine when view onDesstroy because it works automatically! But for the handler, you must call removeCallbacksAndMessages onDestroy

Serg Burlaka
  • 2,351
  • 24
  • 35