When user taps fast on the button the showDialog() method displays multiple times on top of each other, so when you dismiss it there is another one behind it. I am looking for a way to ignore the second tap for 1 second without using a handler or check the previous tap's time.

//Button that opens a dialog
button.setOnClickListener {
    showDialog()
}

我正在寻找一个使用Kotlin协程或Kotlin流的解决方案,用于future 的实现.

推荐答案

最好使用简单的Flag,而不是延迟,因为这不是一个好的用户体验.

但是,如果您想使用协程,您可以简单地使用Kotlin Coroutine's Flow来应用以下内容:

首先,我为click事件创建了一个Extension Function,它返回一个协同程序的流.这样地:

    fun View.clicks(): Flow<Unit> = callbackFlow {
    setOnClickListener {
        offer(Unit)
    }
    awaitClose { setOnClickListener(null) }
   } 

Now, All you need is Calling your Function in onCreate like this:

button.clicks().debounce(1000).onEach { println("clicked") }.launchIn(GlobalScope)

别忘了在build中添加这些行.gradle文件:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'

Edit:

kotlin协同程序中尚未实现throttleFirst运算符的流量模拟.但是,可以通过扩展功能来实现:

@FlowPreview
@ExperimentalCoroutinesApi
fun <T> Flow<T>.throttleFirst(windowDuration: Long): Flow<T> = flow {
    var lastEmissionTime = 0L
    collect { upstream ->
        val currentTime = System.currentTimeMillis()
        val mayEmit = currentTime - lastEmissionTime > windowDuration
        if (mayEmit)
        {
            lastEmissionTime = currentTime
            emit(upstream)
        }
    }
}

The changes are as follows:

binding.button.clicks().throttleFirst(1250)
        .onEach {
            //delay(100)
            showDialog()
        }.launchIn(GlobalScope)

Also, you can use a delay() to handle this. Take it easy to change value of these parameters according to your needs.

Kotlin相关问答推荐

这些Kotlin函数等效吗?

Android前台服务 list —Altbeacon

为什么Kotlin函数参数名会 destruct 方法调用?

Kotlin:有限的并行性并不是限制并行性

我可以更改方法中泛型类的类型参数边界吗?

如何优雅地声明一个StateFlow?

Rabin-Karp字符串匹配的实现(Rolling hash)

使用 StateFlow 时如何移除监听器?

如何缩短 MaterialTheme.colors.primary?

多个不同的指针输入

如何限制 Kotlin 中的枚举?

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

Mockito 的 argThat 在 Kotlin 中返回 null

Jetpack Compose State:修改类属性

在kotlin中,如何模拟封装回调函数?

在调用Kotlin数据类中的超类构造函数之前访问函数

如何在Kotlin中创建填充空值的通用数组?

Android插件2.2.0-alpha1无法使用Kotlin编译

应用程序在使用 Google Play 服务时遇到问题