0

Is there any way to skip a delay in kotlin coroutines.

setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextSubmit(query: String): Boolean {

        // todo: skip the delay

        return true
    }

    private var textChangeCountDown: Job? = null
    override fun onQueryTextChange(text: String): Boolean {
        textChangeCountDown?.cancel()
        textChangeCountDown = lifecycleScope.launch {

            // here is the dalay that need to be skipped when query text submit
            delay(800)

            // text changed to $text

        }
        return true
    }
})

When the user click submit, I want to skip the delay, just something like like:

val mDelay = delay(800)
// mDelay.continue()
// mDelay.cancel()

Is there some function like these?

Bouh
  • 1,303
  • 2
  • 10
  • 24

1 Answers1

1

Try using debounce https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.html

Returns a flow that mirrors the original flow, but filters out values that are followed by the newer values within the given timeout. The latest value is always emitted.

  • 1
    I don't see how I can use `debounce` in my code – Bouh Apr 01 '21 at 11:42
  • 1
    Create a Flow of `queryTextChanged` events and debounce it. Your current code basically does that but with more manual work. Execute the query from `queryTextSubmit`, and while collecting the flow of `queryTextChanged` check that the query you are about to make is not the same as the last one already issued. – Marko Topolnik Apr 01 '21 at 13:15
  • 1
    @Bouh Try this one https://stackoverflow.com/a/63482127/11191424 – Petrus Nguyễn Thái Học Apr 02 '21 at 02:48