Last active
July 13, 2023 10:25
-
-
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 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> { | |
val flow = MutableStateFlow(getItem(key, default)) | |
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k -> | |
if (key == k) { | |
flow.value = getItem(key, default)!! | |
} | |
} | |
registerOnSharedPreferenceChangeListener(listener) | |
return flow | |
.onCompletion { 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 | |
is MutableSet<*> -> getStringSet(key, default as MutableSet<String>) as T | |
else -> throw IllegalArgumentException("generic type not handle ${T::class.java.name}") | |
} | |
} |
I came with this solution:
private fun SharedPreferences.userIdFlow(key: String, defValue: String?): Flow<String?> = callbackFlow {
var currentValue = getString(key, defValue)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
if (k == key) {
val newValue = getString(key, defValue)
if (newValue != currentValue) {
currentValue = newValue
trySend(newValue).isSuccess
}
}
}
registerOnSharedPreferenceChangeListener(listener)
if (currentValue != null && currentValue!!.isNotEmpty()) {
trySend(currentValue).isSuccess // emit current value immediately if not null and not empty
}
awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
}
What's your analysis on it compared to yours?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, @tkubasik-luna your version always produces
Flow<T?>
while the original one returnedFlow<T>
. We provide the default value, so the latter makes more sense to me. And it worked fine when no value is stored for the key, thanks to thedefault
passed togetString
,getInt
, etc.try/catch
could potentially catch the "stored type does not match expected type" kind of errors, but in this case we fail earlier, on line 2. And it's probably good, because this type mismatch is clearly a programmer's mistake which should be fixed.As for cancellation, in my testing both variants cancel/restart on every recomposition when called directly inside composable. I suppose it's inevitable since we're creating a new flow each time. But this is easily solved by wrapping
prefs.observeKey()
inremember
, or better by moving it to a more stable place, e.g.ViewModel
orRepository
. 😃