Skip to content

Commit

Permalink
add PreferencesFlow
Browse files Browse the repository at this point in the history
  • Loading branch information
kroegerama committed Dec 19, 2021
1 parent 638167b commit 7550f24
Showing 1 changed file with 37 additions and 0 deletions.
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) }

0 comments on commit 7550f24

Please sign in to comment.