fix: PreferenceFlowWrapper

This commit is contained in:
septs 2025-02-27 17:09:21 +08:00
parent e6d7fb1b64
commit 0bd64a0ab6
Signed by: septs
SSH key fingerprint: SHA256:ElK0p6DNkbsqYUdJ3I9QHDVf21SQD0c2r+hd7s/r5Co

View file

@ -60,7 +60,8 @@ class PreferenceRepository(private val context: Context) {
class PreferenceFlowWrapper<T> private constructor(
private val context: Context,
private val key: Preferences.Key<T>,
inner: Flow<T>
inner: Flow<T>,
private val setter: suspend (T) -> T = { it }
) : Flow<T> by inner {
internal constructor(context: Context, key: Preferences.Key<T>, defaultValue: T) : this(
context,
@ -69,10 +70,11 @@ class PreferenceFlowWrapper<T> private constructor(
)
suspend fun updatePreference(value: T) {
context.dataStore.edit { it[key] = value }
context.dataStore.edit { it[key] = setter(value) }
}
internal fun with(flow: Flow<T>) = PreferenceFlowWrapper(context, key, flow)
internal fun with(flow: Flow<T> = this, setter: suspend (T) -> T) =
PreferenceFlowWrapper(context, key, flow, setter)
}
fun PreferenceFlowWrapper<Boolean>.negative() = with(map { !it })
fun PreferenceFlowWrapper<Boolean>.negative() = with(map { !it }, { !it })