Skip to content

Instantly share code, notes, and snippets.

@josh-burton
Created February 1, 2018 18:50
Show Gist options
  • Save josh-burton/682b69b6e386ae36900cd95888f4dcb9 to your computer and use it in GitHub Desktop.
Save josh-burton/682b69b6e386ae36900cd95888f4dcb9 to your computer and use it in GitHub Desktop.
A kotlin extension to allow shared preference values to be observed
inline fun <reified T> SharedPreferences.observe(keyToObserve: String, defaultValue: T): Observable<T> {
return Observable.create<T> { emitter ->
val listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
if (key == keyToObserve) {
val value = sharedPreferences.all[key]
if (value is T) {
emitter.onNext(value)
} else {
Timber.w("SharedPreferences", "Warning: observed preference type does not match")
}
}
}
emitter.setCancellable { unregisterOnSharedPreferenceChangeListener(listener) }
registerOnSharedPreferenceChangeListener(listener)
//emit initial value
val initialValue: T = all[keyToObserve]?.run {
if (this is T) {
this
} else {
defaultValue
}
} ?: defaultValue
emitter.onNext(initialValue)
}
.replay(1)
.refCount()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment