Skip to content

Commit

Permalink
perf: 优化高级模式界面卡顿
Browse files Browse the repository at this point in the history
  • Loading branch information
lisonge committed Nov 29, 2023
1 parent 9934221 commit 739cdac
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions app/src/main/java/li/songe/gkd/util/ComposeExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@ import androidx.compose.runtime.MutableState
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.blankj.utilcode.util.ToastUtils
import com.dylanc.activityresult.launcher.PickContentLauncher
import com.dylanc.activityresult.launcher.RequestPermissionLauncher
import com.dylanc.activityresult.launcher.StartActivityLauncher
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext


val LocalLauncher =
Expand All @@ -28,34 +26,21 @@ val LocalRequestPermissionLauncher =
compositionLocalOf<RequestPermissionLauncher> { error("not found RequestPermissionLauncher") }

@Composable
fun <T> usePollState(interval: Long = 1000L, getter: () -> T): MutableState<T> {
fun <T> usePollState(
context: CoroutineContext = Dispatchers.Default,
interval: Long = 1000L,
getter: () -> T,
): MutableState<T> {
val mutableState = remember { mutableStateOf(getter()) }
LaunchedEffect(Unit) {
while (isActive) {
delay(interval)
mutableState.value = getter()
}
}
return mutableState
}

@Composable
fun LaunchedEffectTry(
key1: Any? = null,
block: suspend CoroutineScope.() -> Unit,
) {
LaunchedEffect(key1) {
try {
withContext(IO) {
block()
withContext(context) {
while (isActive) {
delay(interval)
mutableState.value = getter()
}
} catch (e: CancellationException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
ToastUtils.showShort(e.message ?: "")
}
}
return mutableState
}


Expand Down

0 comments on commit 739cdac

Please sign in to comment.