Skip to content

Commit

Permalink
perf: throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
lisonge committed Aug 4, 2024
1 parent d4f1509 commit e86b323
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down
32 changes: 18 additions & 14 deletions app/src/main/kotlin/li/songe/gkd/util/TimeExt.kt
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down

0 comments on commit e86b323

Please sign in to comment.