From 1a99cdbac31462182372bf62f81d5d242a581e9f Mon Sep 17 00:00:00 2001 From: HapeLee <63206378+HapeLee@users.noreply.github.com> Date: Fri, 12 Jun 2026 15:22:05 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=87=AA=E5=8A=A8=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E9=98=85=E8=AF=BB=E6=89=93=E5=BC=80=E5=B4=A9?= =?UTF-8?q?=E6=BA=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/legado/app/ui/config/PrefDelegate.kt | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt b/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt index 969397317..126efd69b 100644 --- a/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt +++ b/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt @@ -3,6 +3,7 @@ package io.legado.app.ui.config import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.snapshots.Snapshot import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.floatPreferencesKey @@ -57,6 +58,9 @@ fun prefDelegate( return object : PrefDelegate, DefaultLifecycleObserver { private var _value: MutableState override val state: State get() = _value + + @Volatile + private var currentValue: T = defaultValue private val scope = CoroutineScope(Dispatchers.IO) private var dsObserverJob: Job? = null @@ -64,6 +68,8 @@ fun prefDelegate( // 同步从 DataStore 读取初始值,确保构造完成后即为最新值 val initialValue = runBlocking(Dispatchers.IO) { readFromDs() } ?: defaultValue _value = mutableStateOf(initialValue) + currentValue = initialValue + // 观察 DataStore 变化,用于跨实例同步 dsObserverJob = scope.launch { appCtx.dataStore.data @@ -91,8 +97,8 @@ fun prefDelegate( } .distinctUntilChanged() .collect { dsValue -> - if (dsValue != null && _value.value != dsValue) { - _value.value = dsValue + if (dsValue != null && currentValue != dsValue) { + updateValue(dsValue) onValueChange?.invoke(dsValue) } } @@ -112,12 +118,12 @@ fun prefDelegate( } override fun getValue(thisRef: Any?, property: KProperty<*>): T { - return _value.value + return currentValue } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { - if (_value.value != value) { - _value.value = value + if (currentValue != value) { + updateValue(value) // 同步写入 SP(向后兼容:AppConfig/MainViewModel 等仍直接读 SP) when (value) { is String? -> if (sync) appCtx.putPrefStringSync(key, value) else appCtx.putPrefString(key, value) @@ -204,6 +210,13 @@ fun prefDelegate( } return spValue } + + private fun updateValue(value: T) { + currentValue = value + Snapshot.withMutableSnapshot { + _value.value = value + } + } } }