diff --git a/app/src/main/kotlin/li/songe/gkd/ui/component/DialogOptions.kt b/app/src/main/kotlin/li/songe/gkd/ui/component/DialogOptions.kt index 60e042d..65490bb 100644 --- a/app/src/main/kotlin/li/songe/gkd/ui/component/DialogOptions.kt +++ b/app/src/main/kotlin/li/songe/gkd/ui/component/DialogOptions.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.getValue import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.yield +import li.songe.gkd.util.throttle import kotlin.coroutines.coroutineContext import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @@ -39,13 +40,13 @@ fun buildDialogOptions( }, onDismissRequest = onDismissRequest, confirmButton = { - TextButton(onClick = confirmAction) { + TextButton(onClick = throttle(fn = confirmAction)) { Text(text = confirmText) } }, dismissButton = if (dismissText != null && dismissAction != null) { { - TextButton(onClick = dismissAction) { + TextButton(onClick = throttle(fn = dismissAction)) { Text(text = dismissText) } } diff --git a/app/src/main/kotlin/li/songe/gkd/util/TimeExt.kt b/app/src/main/kotlin/li/songe/gkd/util/TimeExt.kt index 07421d5..070e0ac 100644 --- a/app/src/main/kotlin/li/songe/gkd/util/TimeExt.kt +++ b/app/src/main/kotlin/li/songe/gkd/util/TimeExt.kt @@ -1,6 +1,5 @@ package li.songe.gkd.util -import li.songe.gkd.data.Value import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit @@ -37,34 +36,39 @@ fun Long.format(formatStr: String): String { return df.format(this) } -private val defaultThrottleTimer by lazy { - Value(0L) +data class ThrottleTimer( + private val interval: Long = 1000L, + private var value: Long = 0L +) { + fun expired(): Boolean { + val t = System.currentTimeMillis() + if (t - value > interval) { + value = t + return true + } + return false + } } -private const val defaultThrottleInterval = 1000L + +private val defaultThrottleTimer by lazy { ThrottleTimer() } fun throttle( - interval: Long = defaultThrottleInterval, - timer: Value = defaultThrottleTimer, + timer: ThrottleTimer = defaultThrottleTimer, fn: (() -> Unit), ): (() -> Unit) { return { - val t = System.currentTimeMillis() - if (t - timer.value > interval) { - timer.value = t + if (timer.expired()) { fn.invoke() } } } fun throttle( - interval: Long = defaultThrottleInterval, - timer: Value = defaultThrottleTimer, + timer: ThrottleTimer = defaultThrottleTimer, fn: ((T) -> Unit), ): ((T) -> Unit) { return { - val t = System.currentTimeMillis() - if (t - timer.value > interval) { - timer.value = t + if (timer.expired()) { fn.invoke(it) } }