-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
638167b
commit 7550f24
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
core/src/main/kotlin/com/kroegerama/kaiteki/architecture/PreferencesFlow.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package com.kroegerama.kaiteki.architecture | ||
|
||
import android.content.SharedPreferences | ||
import android.util.Log | ||
import kotlinx.coroutines.channels.awaitClose | ||
import kotlinx.coroutines.channels.trySendBlocking | ||
import kotlinx.coroutines.flow.Flow | ||
import kotlinx.coroutines.flow.callbackFlow | ||
|
||
private fun <T> SharedPreferences.flow( | ||
key: String, | ||
getter: () -> T | ||
): Flow<T?> = callbackFlow { | ||
fun getOrNull() = if (contains(key)) getter() else null | ||
|
||
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, callbackKey -> | ||
Log.d("PrefsFlow", "KEY $callbackKey") | ||
if (callbackKey == key) { | ||
trySendBlocking(getOrNull()) | ||
} | ||
} | ||
trySend(getOrNull()) | ||
registerOnSharedPreferenceChangeListener(listener) | ||
awaitClose { | ||
unregisterOnSharedPreferenceChangeListener(listener) | ||
} | ||
} | ||
|
||
fun SharedPreferences.intFlow(key: String) = flow(key) { getInt(key, 0) } | ||
|
||
fun SharedPreferences.longFlow(key: String) = flow(key) { getLong(key, 0L) } | ||
|
||
fun SharedPreferences.floatFlow(key: String) = flow(key) { getFloat(key, 0f) } | ||
|
||
fun SharedPreferences.booleanFlow(key: String) = flow(key) { getBoolean(key, false) } | ||
|
||
fun SharedPreferences.stringFlow(key: String) = flow(key) { getString(key, null) } |