Skip to content

Instantly share code, notes, and snippets.

@mehdisamavat
Forked from ologe/PreferenceExtensions.kt
Created February 1, 2023 17:17
Show Gist options
  • Save mehdisamavat/5cc0e86f497ec82e0cf062827b18d784 to your computer and use it in GitHub Desktop.
Save mehdisamavat/5cc0e86f497ec82e0cf062827b18d784 to your computer and use it in GitHub Desktop.
Android shared preference observer using kotlin coroutines (1.3.0)
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}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment