Refine: make synchronous pref writes opt-in via sync parameter

Only use commit() (sync disk write) for preferences that opt in with
sync=true. The language preference in OtherConfig is currently the only
one that needs this — it triggers an immediate process restart via
context.restart().

Other string preferences continue using apply() (async) to avoid
unnecessary main-thread blocking.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Isilsolme
2026-05-31 19:51:35 +08:00
co-authored by Claude Opus 4.8
parent 59468d1bc2
commit 6ebe36dec9
2 changed files with 6 additions and 3 deletions
@@ -35,6 +35,7 @@ fun <T> prefDelegate(
key: String,
defaultValue: T,
lifecycleOwner: LifecycleOwner? = null,
sync: Boolean = false,
onValueChange: ((T) -> Unit)? = null
): PrefDelegate<T> {
return object : PrefDelegate<T>, SharedPreferences.OnSharedPreferenceChangeListener, DefaultLifecycleObserver {
@@ -85,7 +86,7 @@ fun <T> prefDelegate(
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (_value.value != value) {
when (value) {
is String? -> appCtx.putPrefStringSync(key, value)
is String? -> if (sync) appCtx.putPrefStringSync(key, value) else appCtx.putPrefString(key, value)
is Int -> appCtx.putPrefInt(key, value)
is Boolean -> appCtx.putPrefBoolean(key, value)
is Long -> appCtx.putPrefLong(key, value)
@@ -112,8 +113,9 @@ fun <T> prefStateDelegate(
key: String,
defaultValue: T,
lifecycleOwner: LifecycleOwner? = null,
sync: Boolean = false,
onValueChange: ((T) -> Unit)? = null
): PrefStateDelegate<T> {
val delegate = prefDelegate(key, defaultValue, lifecycleOwner, onValueChange)
val delegate = prefDelegate(key, defaultValue, lifecycleOwner, sync, onValueChange)
return PrefStateDelegate(delegate)
}
@@ -8,7 +8,8 @@ object OtherConfig {
var language by prefDelegate(
PreferKey.language,
"auto"
"auto",
sync = true
)
var updateToVariant by prefDelegate(