Merge pull request #1889 from esensar/feature/preferences-callbacks

Add `sendOnCollect` flag to `sharedPreferencesCallback` for consistent values flow
This commit is contained in:
Tibor Kaputa 2023-10-16 09:51:34 +02:00 committed by GitHub
commit fd497d3719
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 2 deletions

View file

@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.callbackFlow
context (SharedPreferences)
fun <T> sharedPreferencesCallback(
sendOnCollect: Boolean = false,
value: () -> T?,
): Flow<T?> = callbackFlow {
val sharedPreferencesListener =
@ -14,6 +15,9 @@ fun <T> sharedPreferencesCallback(
trySend(value())
}
if (sendOnCollect) {
trySend(value())
}
registerOnSharedPreferenceChangeListener(sharedPreferencesListener)
awaitClose { unregisterOnSharedPreferenceChangeListener(sharedPreferencesListener) }
}

View file

@ -610,7 +610,7 @@ open class BaseConfig(val context: Context) {
get() = prefs.getLong(PASSWORD_COUNTDOWN_START_MS, 0L)
set(passwordCountdownStartMs) = prefs.edit().putLong(PASSWORD_COUNTDOWN_START_MS, passwordCountdownStartMs).apply()
protected fun <T> KProperty0<T>.asFlow(): Flow<T?> = prefs.run { sharedPreferencesCallback { this@asFlow.get() } }
protected fun <T> KProperty0<T>.asFlow(emitOnCollect: Boolean = false): Flow<T?> = prefs.run { sharedPreferencesCallback(sendOnCollect = emitOnCollect) { this@asFlow.get() } }
protected fun <T> KProperty0<T>.asFlowNonNull(): Flow<T> = asFlow().filterNotNull()
protected fun <T> KProperty0<T>.asFlowNonNull(emitOnCollect: Boolean = false): Flow<T> = asFlow(emitOnCollect).filterNotNull()
}