From fae2b1f416033edcb800ea8aa6f8a3b0c0b0cc6f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <99822064+revonateB0T@users.noreply.github.com> Date: Fri, 10 May 2024 14:15:18 +0800 Subject: [PATCH] Cleanup `rememberInVM` family (#1166) * Update DataStore to 1.1.1 for future `rememberInDataStore` impl * Cleanup `rememberInVM` family --------- Co-authored-by: GG Bond --- .../ehviewer/ui/tools/RememberGlobally.kt | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/app/src/main/kotlin/com/hippo/ehviewer/ui/tools/RememberGlobally.kt b/app/src/main/kotlin/com/hippo/ehviewer/ui/tools/RememberGlobally.kt index 234d5ec48..6f0b3d004 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/ui/tools/RememberGlobally.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/ui/tools/RememberGlobally.kt @@ -3,8 +3,8 @@ package com.hippo.ehviewer.ui.tools import androidx.compose.runtime.Composable import androidx.compose.runtime.DisallowComposableCalls import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.State import androidx.compose.runtime.currentCompositeKeyHash +import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState @@ -18,28 +18,27 @@ import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.launch class StateMapViewModel : ViewModel() { - val states: MutableMap> = mutableMapOf() + val statesMap = mutableMapOf>() } @Composable inline fun rememberInVM( vararg inputs: Any?, crossinline init: @DisallowComposableCalls ViewModel.() -> T, -): T { - val vm: StateMapViewModel = viewModel() +) = with(viewModel()) { val key = currentCompositeKeyHash - val value = remember(*inputs) { - val states = vm.states[key] ?: ArrayDeque().also { vm.states[key] = it } + remember(*inputs) { + val states = statesMap[key] ?: ArrayDeque().also { statesMap[key] = it } @Suppress("UNCHECKED_CAST") - states.removeLastOrNull() as T? ?: init(vm) - } - val valueState = rememberUpdatedState(value) - DisposableEffect(key) { - onDispose { - vm.states[key]?.addFirst(valueState.value) + states.removeLastOrNull() as T? ?: init() + }.also { value -> + val valueState by rememberUpdatedState(value) + DisposableEffect(key) { + onDispose { + statesMap[key]?.addFirst(valueState) + } } } - return value } @Composable @@ -52,6 +51,4 @@ fun launchInVM( } @Composable -fun rememberUpdatedStateInVM(newValue: T): State = rememberInVM { - mutableStateOf(newValue) -}.apply { value = newValue } +fun rememberUpdatedStateInVM(newValue: T) = rememberInVM { mutableStateOf(newValue) }.apply { value = newValue }