Last active
July 27, 2019 11:23
-
-
Save ibrahimsn98/d367ae04a7e8adb97838247e64aa29b8 to your computer and use it in GitHub Desktop.
Android-Live-Shared-Preferences-Gist3
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
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