Last active
July 27, 2019 11:20
-
-
Save ibrahimsn98/239675579b88d0d047a14f40d92b62ff to your computer and use it in GitHub Desktop.
Android-Live-Shared-Preferences-Gist6
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 MultiPreference<T> constructor(private val updates: Observable<String>, | |
private val preferences: SharedPreferences, | |
private val keys: List<String>, | |
private val defaultValue: T) : MutableLiveData<Map<String, T>>() { | |
private var disposable: Disposable? = null | |
private val values = mutableMapOf<String, T>() | |
init { | |
for (key in keys) | |
values[key] = preferences.all[key] as T ?: defaultValue | |
} | |
override fun onActive() { | |
super.onActive() | |
value = values | |
disposable = updates.filter { t -> keys.contains(t) }.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()).subscribeWith(object: DisposableObserver<String>() { | |
override fun onComplete() { | |
} | |
override fun onNext(t: String) { | |
values[t] = preferences.all[t] as T ?: defaultValue | |
postValue(values) | |
} | |
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