Home » Android » java – Try to write `coroutine` analog for `handler`, but not work-Exceptionshub

java – Try to write `coroutine` analog for `handler`, but not work-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

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?

How to&Answers:

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