From 8d12e03113c46adb958154d3f6e0e55214dd5884 Mon Sep 17 00:00:00 2001 From: HapeLee <63206378+HapeLee@users.noreply.github.com> Date: Mon, 8 Jun 2026 13:49:54 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=85=8D=E7=BD=AE=E6=97=A0=E5=93=8D?= =?UTF-8?q?=E5=BA=94=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/io/legado/app/ui/config/PrefDelegate.kt | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 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 7c2812c66..258d87382 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 @@ -19,6 +19,7 @@ import io.legado.app.utils.putPrefStringSync import io.legado.app.help.config.DsSync import androidx.datastore.preferences.core.* import io.legado.app.data.repository.dataStore +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -28,6 +29,7 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import splitties.init.appCtx import java.io.IOException import kotlin.properties.ReadWriteProperty @@ -35,11 +37,13 @@ import kotlin.reflect.KProperty interface PrefDelegate : ReadWriteProperty { val state: State + val ready: CompletableDeferred fun dispose() } class PrefStateDelegate(private val delegate: PrefDelegate) : ReadWriteProperty by delegate { val state: State get() = delegate.state + val ready: CompletableDeferred get() = delegate.ready } fun prefDelegate( @@ -54,14 +58,19 @@ fun prefDelegate( override val state: State get() = _value private val scope = CoroutineScope(Dispatchers.IO) private var dsObserverJob: Job? = null + override val ready = CompletableDeferred() init { // 从 DataStore 读取初始值(DS 为唯一读取源) + // 在 IO 线程读取,切换到 Main 线程更新 MutableState,确保 snapshotFlow 能检测到变化 scope.launch { val dsValue = readFromDs() if (dsValue != null) { - _value.value = dsValue + withContext(Dispatchers.Main) { + _value.value = dsValue + } } + ready.complete(Unit) } // 观察 DataStore 变化,用于跨实例同步 dsObserverJob = scope.launch { @@ -91,7 +100,9 @@ fun prefDelegate( .distinctUntilChanged() .collect { dsValue -> if (dsValue != null && _value.value != dsValue) { - _value.value = dsValue + withContext(Dispatchers.Main) { + _value.value = dsValue + } onValueChange?.invoke(dsValue) } } @@ -126,7 +137,6 @@ fun prefDelegate( is Float -> appCtx.putPrefFloat(key, value) } // 同步写入 DataStore,确保持久化后再返回 - // 异常不阻断流程:SP 已写入,readFromDs() 会回退到 SP 读取 runCatching { runBlocking(Dispatchers.IO) { when (value) {