I am trying to create a Flow based on shared preferences properties. To achieve this, I have defined two functions:
fun <T> getPreferenceAsFlow(keyValue: String, defValue: T?) = callbackFlow {
val transformedKey = toKey(keyValue)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == transformedKey) {
trySend(preferenceValueFlow<T?>(keyValue, defValue))
}
}
mSharedPreferences.registerOnSharedPreferenceChangeListener(listener)
if (mSharedPreferences.contains(transformedKey)) {
send(preferenceValueFlow<T?>(keyValue, defValue)) // if you want to emit an initial pre-existing value
}
awaitClose { mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) }
}.buffer(Channel.UNLIMITED)
@Suppress("UNCHECKED_CAST")
private fun <T> preferenceValueFlow(keyValue: String, defValue: T?): T? {
return when (T::class) {
String::class -> getString(key = keyValue, defValue as String?) as T?
Boolean::class -> getBoolean(key = keyValue, defValue?.let { it as Boolean } ?: false) as T?
Int::class -> getInteger(key = keyValue, defValue as Int?) as T?
Long::class -> getLong(key = keyValue, defValue as Long?) as T?
else -> {
throw IllegalArgumentException("Preference type not supported: ${T::class.java.name}")
}
}
}
But when I define the variable flow like this:
val lastAppDataUpdateDate: Flow<Long?> = securePrefs.getPreferenceAsFlow("key", null)
I am expecting to get a Long, but instead I have a Int, so I have a NumberFormatException.
I am trying to figure out what I am doing wrong without success.
Any idea?
Thanks in advance