Skip to content

Commit

Permalink
🐛: fix: #25;
Browse files Browse the repository at this point in the history
  • Loading branch information
junerver committed Sep 4, 2024
1 parent 0439aa1 commit 5c2ff82
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ val fetchStore = createStore {
private fun <T> useFetchAliasFetch(
alias: String,
autoFetch: Boolean = false,
errorRetry:Int = 0,
errorRetry: Int = 0,
block: suspend CoroutineScope.() -> T,
): Tuple2<NetFetchResult<T>, () -> Unit> {
val fetchResult: NetFetchResult<T> = useSelector(alias)
Expand All @@ -332,14 +332,14 @@ private fun <T> useFetchAliasFetch(
if (autoFetch) fetch()
}
// 错误重试
when(fetchResult){
is NetFetchResult.Error->{
when (fetchResult) {
is NetFetchResult.Error -> {
if (retryCount.current > 0) {
fetch()
retryCount.current --
retryCount.current--
}
}
else->{}
else -> {}
}
return tuple(
first = fetchResult,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.datetime.Clock
import xyz.junerver.compose.hooks.invoke
import xyz.junerver.compose.hooks.optionsOf
import xyz.junerver.compose.hooks.useEffect
import xyz.junerver.compose.hooks.useGetState
import xyz.junerver.compose.hooks.useThrottle
import xyz.junerver.compose.hooks.useThrottleEffect
Expand All @@ -33,7 +36,16 @@ fun UseThrottleExample() {

// for useThrottleFn
val (stateFn, setStateFn) = useGetState(0)
val throttledFn = useThrottleFn(fn = { setStateFn(stateFn + 1) })
val throttledFn = useThrottleFn(
fn = { setStateFn(stateFn + 1) },
optionsOf {
leading = false
trailing = false
}
)
useEffect(stateFn) {
println("$stateFn: ${Clock.System.now()}")
}

// for throttleEffect
val (stateEf, setStateEf) = useGetState(0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package xyz.junerver.compose.hooks
import androidx.compose.runtime.Composable
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import xyz.junerver.compose.hooks.utils.currentTime
import xyz.junerver.kotlin.Tuple2
import xyz.junerver.kotlin.asBoolean

Expand Down Expand Up @@ -42,7 +42,7 @@ fun useCountdown(options: CountdownOptions): Tuple2<Duration, FormattedRes> {
val (leftTime, targetDate, interval, onEnd) = options
val target = useCreation {
if (leftTime.asBoolean()) {
Clock.System.now() + leftTime
currentTime + leftTime
} else {
targetDate
}
Expand Down Expand Up @@ -81,7 +81,7 @@ fun useCountdown(options: CountdownOptions): Tuple2<Duration, FormattedRes> {

private fun calcLeft(target: Instant?): Duration {
if (target == null) return 0.seconds
val left = target - Clock.System.now()
val left = target - currentTime
return if (left < 0.seconds) 0.seconds else left
}

Expand Down
17 changes: 7 additions & 10 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/useDebounce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import xyz.junerver.compose.hooks.utils.currentTime
import xyz.junerver.kotlin.Tuple2

Expand Down Expand Up @@ -42,8 +42,8 @@ internal class Debounce(

private var calledCount = 0
private val jobs: MutableList<Tuple2<Job, Boolean>> = arrayListOf()
private var latestInvokedTime = Clock.System.now()
private var latestCalledTime = Clock.System.now()
private var latestInvokedTime = Instant.DISTANT_PAST
private var latestCalledTime = latestInvokedTime

private fun clear() {
if (jobs.isNotEmpty()) {
Expand All @@ -59,21 +59,18 @@ internal class Debounce(
override fun invoke(p1: TParams) {
val (wait, leading, trailing, maxWait) = options
fun task(guarantee: Boolean, isDelay: Boolean) {
if (guarantee) {
latestInvokedTime = Clock.System.now()
}
scope.launch {
if (isDelay) delay(wait)
fn(p1)
latestInvokedTime = Clock.System.now()
latestInvokedTime = currentTime
}.also { jobs.add(it to guarantee) }
}

val waitTime = currentTime - latestInvokedTime
val interval = currentTime - latestCalledTime
val isMaxWait = maxWait in 1.milliseconds..waitTime
if (isMaxWait || (calledCount == 0 && leading)) {
task(guarantee = isMaxWait, isDelay = false)
if ((isMaxWait && calledCount != 0) || (calledCount == 0 && leading)) {
task(guarantee = true, isDelay = false)
} else {
if (calledCount > 0 && interval < wait) {
clear()
Expand All @@ -85,7 +82,7 @@ internal class Debounce(
}
}
calledCount++
latestCalledTime = Clock.System.now()
latestCalledTime = currentTime
}
}

Expand Down
23 changes: 9 additions & 14 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/useThrottle.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import xyz.junerver.compose.hooks.utils.currentTime

/**
* Throttle options
Expand Down Expand Up @@ -52,31 +52,26 @@ internal class Throttle(

override fun invoke(p1: TParams) {
val (wait, leading, trailing) = options
val waitTime = Clock.System.now() - latestInvokedTime
val waitTime = currentTime - latestInvokedTime

fun task(isDelay: Boolean, isTrailing: Boolean = false) {
scope.launch(start = if (isTrailing) CoroutineStart.LAZY else CoroutineStart.DEFAULT) {
if (isDelay) delay(wait)
fun task(isTrailing: Boolean) {
scope.launch(start = CoroutineStart.DEFAULT) {
if (isTrailing) delay(wait)
fn(p1)
if (!isTrailing && trailingJobs.isNotEmpty()) {
trailingJobs.last().apply {
start()
join()
}
}
if (isTrailing) latestInvokedTime = currentTime
}.also {
if (isTrailing) {
trailingJobs.add(it)
}
}
}
if (waitTime > wait) {
task(isDelay = !(calledCount == 0 && leading))
latestInvokedTime = Clock.System.now()
task(isTrailing = calledCount == 0 && !leading)
latestInvokedTime = currentTime
} else {
if (trailing) {
clearTrailing()
task(isDelay = true, isTrailing = true)
task(isTrailing = true)
}
}
calledCount++
Expand Down
10 changes: 5 additions & 5 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/useTimestamp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.datetime.Clock
import xyz.junerver.compose.hooks.utils.currentTime
import xyz.junerver.kotlin.Tuple4
import xyz.junerver.kotlin.tuple

Expand Down Expand Up @@ -45,13 +45,13 @@ fun useTimestamp(
autoResume: Boolean = true,
): Tuple4<Long, PauseFn, ResumeFn, IsActive> {
val (interval, offset, callback) = with(options) { tuple(interval, offset, callback) }
var timestamp by useState(default = Clock.System.now())
var timestamp by useState(default = currentTime)
val (resume, pause, isActive) = useInterval(
optionsOf {
period = interval
}
) {
timestamp = Clock.System.now() + offset
timestamp = currentTime + offset
callback?.invoke(timestamp.toEpochMilliseconds())
}
useMount {
Expand All @@ -78,13 +78,13 @@ fun useTimestampRef(
autoResume: Boolean = true,
): Tuple4<Ref<Long>, PauseFn, ResumeFn, IsActive> {
val (interval, offset, callback) = with(options) { tuple(interval, offset, callback) }
val timestampRef = useRef(default = Clock.System.now().toEpochMilliseconds())
val timestampRef = useRef(default = currentTime.toEpochMilliseconds())
val (resume, pause, isActive) = useInterval(
optionsOf {
period = interval
}
) {
timestampRef.current = (Clock.System.now() + offset).toEpochMilliseconds()
timestampRef.current = (currentTime + offset).toEpochMilliseconds()
callback?.invoke(timestampRef.current)
}
useMount {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import xyz.junerver.compose.hooks.utils.currentTime

/*
Description:
Expand All @@ -35,19 +35,19 @@ internal class InactivityWindowCallback(
private val isTimeoutCallback: (Boolean, Instant) -> Unit,
) : Window.Callback {

private var lastActiveTime = Clock.System.now()
private var lastActiveTime = currentTime

init {
scope.launch {
while (isActive) {
isTimeoutCallback(Clock.System.now() - lastActiveTime > timeout, lastActiveTime)
isTimeoutCallback(currentTime - lastActiveTime > timeout, lastActiveTime)
delay(interval)
}
}
}

private fun updateLastInteractionTime() {
lastActiveTime = Clock.System.now()
lastActiveTime = currentTime
}

override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import xyz.junerver.compose.hooks.useState
import xyz.junerver.compose.hooks.utils.currentTime
import xyz.junerver.kotlin.Tuple2

/*
Expand All @@ -27,7 +27,7 @@ import xyz.junerver.kotlin.Tuple2
fun useIdle(timeout: Duration = 5.seconds): Tuple2<Boolean, Instant> {
val window = (LocalContext.current as Activity).window
var idle by useState(default = false)
var lastActive by useState(default = Clock.System.now())
var lastActive by useState(default = currentTime)
val originalCallback = remember { window.callback }
val scope = rememberCoroutineScope()
DisposableEffect(key1 = Unit) {
Expand Down

0 comments on commit 5c2ff82

Please sign in to comment.