Skip to content

Instantly share code, notes, and snippets.

@ibrahimsn98
Last active July 27, 2019 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibrahimsn98/d367ae04a7e8adb97838247e64aa29b8 to your computer and use it in GitHub Desktop.
Save ibrahimsn98/d367ae04a7e8adb97838247e64aa29b8 to your computer and use it in GitHub Desktop.
Android-Live-Shared-Preferences-Gist3
class LivePreference<T> constructor(private val updates: Observable<String>,
private val preferences: SharedPreferences,
private val key: String,
private val defaultValue: T) : MutableLiveData<T>() {
private var disposable: Disposable? = null
override fun onActive() {
super.onActive()
value = (preferences.all[key] as T) ?: defaultValue
disposable = updates.filter { t -> t == key }.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribeWith(object: DisposableObserver<String>() {
override fun onComplete() {
}
override fun onNext(t: String) {
postValue((preferences.all[t] as T) ?: defaultValue)
}
override fun onError(e: Throwable) {
}
})
}
override fun onInactive() {
super.onInactive()
disposable?.dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment