Merge pull request #1889 from esensar/feature/preferences-callbacks
Add `sendOnCollect` flag to `sharedPreferencesCallback` for consistent values flow
This commit is contained in:
commit
fd497d3719
2 changed files with 6 additions and 2 deletions
|
@ -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) }
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue