Last active
November 13, 2024 21:10
-
-
Save ologe/eaa1dea1f94cdda1a39adcaf3886658a to your computer and use it in GitHub Desktop.
Android shared preference observer using kotlin coroutines (1.3.0)
This file contains hidden or 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
inline fun <reified T> SharedPreferences.observeKey(key: String, default: T): Flow<T> = channelFlow { | |
send(getItem(key, default)) | |
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k -> | |
if (key == k) { | |
trySend(getItem(key, default)) | |
} | |
} | |
registerOnSharedPreferenceChangeListener(listener) | |
awaitClose { | |
unregisterOnSharedPreferenceChangeListener(listener) | |
} | |
} | |
inline fun <reified T> SharedPreferences.getItem(key: String, default: T): T { | |
@Suppress("UNCHECKED_CAST") | |
return when (default) { | |
is String -> getString(key, default) as T | |
is Int -> getInt(key, default) as T | |
is Long -> getLong(key, default) as T | |
is Boolean -> getBoolean(key, default) as T | |
is Float -> getFloat(key, default) as T | |
is Set<*> -> getStringSet(key, default as Set<String>) as T | |
else -> error("generic type not handled ${T::class.java.name}") | |
} | |
} |
What I'm using now is kind of a mix between @ologe's and @mobilekosmos 's approach:
inline fun <reified T> SharedPreferences.observeKey(
coroutineScope: CoroutineScope,
coroutineContextProvider: CoroutineContextProvider,
key: String,
default: T,
): Flow<T> = callbackFlow {
trySend(getItem(coroutineContextProvider, key, default))
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
if (k == key) {
coroutineScope.launch {
trySend(getItem(coroutineContextProvider, key, default))
}
}
}
registerOnSharedPreferenceChangeListener(listener)
awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
}.conflate()
suspend inline fun <reified T> SharedPreferences.getItem(
coroutineContextProvider: CoroutineContextProvider,
key: String,
default: T,
): T = withContext(coroutineContextProvider.io) {
@Suppress("UNCHECKED_CAST")
when (default) {
is String -> getString(key, default) as T
is Int -> getInt(key, default) as T
is Long -> getLong(key, default) as T
is Boolean -> getBoolean(key, default) as T
is Float -> getFloat(key, default) as T
is Set<*> -> getStringSet(key, default as Set<String>) as T
else -> throw IllegalArgumentException("generic type not handle ${T::class.java.name}")
}
}
@ubuntudroid yeah probably handling MutableSet is not actually needed, I think the initial thought was that kotlin.collection.MutableSet
translated into java.util.Set
btw about switching dispatcher, I think is unnecessary because if I remember correctly SharedPreferences is just a glorified HashMap, and everything is stored (additionally) in memory, the expensive part of the api is writing to disk
I'm also updating the gist to what I think is the cleanest way after almost 4 years 😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mobilekosmos as
MutableSet
is always also aSet
, your code would never return aMutableSet
.Then again: why would you want to put a
MutableSet
intoSharedPreferences
in the first place? It would lose its mutability anyway the moment you serialize. And when you return it, you actually only ever get an immutable set. Which one could then make a mutable set at the call site, if needed.I would just remove that when branch altogether.