fix: dataStore逻辑
This commit is contained in:
@@ -59,6 +59,7 @@ fun <T> prefDelegate(
|
||||
// 从 DataStore 读取初始值(DS 为唯一读取源)
|
||||
scope.launch {
|
||||
val dsValue = readFromDs()
|
||||
android.util.Log.d("PrefDelegate", "readFromDs key=$key defaultValue=$defaultValue dsValue=$dsValue")
|
||||
if (dsValue != null) {
|
||||
_value.value = dsValue
|
||||
}
|
||||
@@ -127,7 +128,7 @@ fun <T> prefDelegate(
|
||||
}
|
||||
// 同步写入 DataStore,确保持久化后再返回
|
||||
// 异常不阻断流程:SP 已写入,readFromDs() 会回退到 SP 读取
|
||||
runCatching {
|
||||
val dsResult = runCatching {
|
||||
runBlocking(Dispatchers.IO) {
|
||||
when (value) {
|
||||
is String? -> DsSync.putString(key, value)
|
||||
@@ -138,6 +139,7 @@ fun <T> prefDelegate(
|
||||
}
|
||||
}
|
||||
}
|
||||
android.util.Log.d("PrefDelegate", "setValue key=$key value=$value dsResult=${dsResult.isSuccess}")
|
||||
onValueChange?.invoke(value)
|
||||
}
|
||||
}
|
||||
@@ -175,8 +177,12 @@ fun <T> prefDelegate(
|
||||
null
|
||||
}
|
||||
// DS 有值,直接返回
|
||||
if (dsValue != null) return dsValue
|
||||
if (dsValue != null) {
|
||||
android.util.Log.d("PrefDelegate", "readFromDs key=$key DS hit=$dsValue")
|
||||
return dsValue
|
||||
}
|
||||
// DS 无值,回退到 SP(迁移遗漏时的补偿)
|
||||
android.util.Log.d("PrefDelegate", "readFromDs key=$key DS miss, falling back to SP")
|
||||
val spValue: T? = when {
|
||||
defaultValue is String || defaultValue == null ->
|
||||
appCtx.getPrefString(key, defaultValue as String?) as T?
|
||||
@@ -190,16 +196,19 @@ fun <T> prefDelegate(
|
||||
appCtx.getPrefFloat(key, defaultValue) as T
|
||||
else -> null
|
||||
}
|
||||
// SP 有值但 DS 没有,补写入 DS 修复迁移遗漏
|
||||
if (spValue != null && spValue != defaultValue) {
|
||||
when (spValue) {
|
||||
is String? -> DsSync.putString(key, spValue)
|
||||
is Int -> DsSync.putInt(key, spValue)
|
||||
is Boolean -> DsSync.putBoolean(key, spValue)
|
||||
is Long -> DsSync.putLong(key, spValue)
|
||||
is Float -> DsSync.putFloat(key, spValue)
|
||||
// DS 无值时,将 SP 值补写入 DS(修复迁移遗漏)
|
||||
if (spValue != null) {
|
||||
runCatching {
|
||||
when (spValue) {
|
||||
is String? -> DsSync.putString(key, spValue)
|
||||
is Int -> DsSync.putInt(key, spValue)
|
||||
is Boolean -> DsSync.putBoolean(key, spValue)
|
||||
is Long -> DsSync.putLong(key, spValue)
|
||||
is Float -> DsSync.putFloat(key, spValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
android.util.Log.d("PrefDelegate", "readFromDs key=$key SP fallback=$spValue (defaultValue=$defaultValue)")
|
||||
return spValue
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user