From 7550f24a452bc905af951914947e1fbb8ade66b8 Mon Sep 17 00:00:00 2001 From: kroegerama <1519044+kroegerama@users.noreply.github.com> Date: Sun, 19 Dec 2021 18:54:48 +0100 Subject: [PATCH] add `PreferencesFlow` --- .../kaiteki/architecture/PreferencesFlow.kt | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 core/src/main/kotlin/com/kroegerama/kaiteki/architecture/PreferencesFlow.kt diff --git a/core/src/main/kotlin/com/kroegerama/kaiteki/architecture/PreferencesFlow.kt b/core/src/main/kotlin/com/kroegerama/kaiteki/architecture/PreferencesFlow.kt new file mode 100644 index 0000000..552d1ce --- /dev/null +++ b/core/src/main/kotlin/com/kroegerama/kaiteki/architecture/PreferencesFlow.kt @@ -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 SharedPreferences.flow( + key: String, + getter: () -> T +): Flow = 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) }