【问题标题】:skip delay in kotlin coroutines跳过 kotlin 协程中的延迟
【发布时间】:2021-06-27 23:50:43
【问题描述】:

有什么办法可以跳过 kotlin 协程中的延迟。

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
    }
})

当用户点击提交时,我想跳过延迟,就像这样:

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

有这样的功能吗?

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    尝试使用debounce https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.html

    返回一个镜像原始流的流,但在给定的超时时间内过滤掉后面跟着新值的值。总是发出最新的值。

    【讨论】:

    • 我不知道如何在我的代码中使用debounce
    • 创建queryTextChanged 事件流并对其进行去抖动。您当前的代码基本上可以做到这一点,但需要更多的手动工作。执行来自queryTextSubmit的查询,并在收集queryTextChanged的流量时检查您即将进行的查询与已发出的最后一个不同。
    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2020-09-15
    • 2018-04-20
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2021-06-25
    相关资源
    最近更新 更多