perf: throttle
Some checks are pending
Build-Apk / build (push) Waiting to run

This commit is contained in:
lisonge 2024-08-04 19:04:52 +08:00
parent d4f1509b85
commit e86b323906
2 changed files with 21 additions and 16 deletions

View File

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

View File

@ -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<Long> = 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 <T> throttle(
interval: Long = defaultThrottleInterval,
timer: Value<Long> = 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)
}
}