Skip to content

Instantly share code, notes, and snippets.

@idish
Created January 30, 2019 23:18
Show Gist options
  • Save idish/f46a8327da7f293f943a5bda31078c95 to your computer and use it in GitHub Desktop.
Save idish/f46a8327da7f293f943a5bda31078c95 to your computer and use it in GitHub Desktop.
abstract class SharedPreferenceLiveData<T> extends LiveData<T> {
SharedPreferences sharedPrefs;
String key;
T defValue;
public SharedPreferenceLiveData(SharedPreferences prefs, String key, T defValue) {
this.sharedPrefs = prefs;
this.key = key;
this.defValue = defValue;
}
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (SharedPreferenceLiveData.this.key.equals(key)) {
setValue(getValueFromPreferences(key, defValue));
}
}
};
abstract T getValueFromPreferences(String key, T defValue);
@Override
protected void onActive() {
super.onActive();
setValue(getValueFromPreferences(key, defValue));
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
@Override
protected void onInactive() {
sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
super.onInactive();
}
}
public class SharedPreferenceBooleanLiveData extends SharedPreferenceLiveData<Boolean>{
public SharedPreferenceBooleanLiveData(SharedPreferences prefs, String key, Boolean defValue) {
super(prefs, key, defValue);
}
@Override
Boolean getValueFromPreferences(String key, Boolean defValue) {
return sharedPrefs.getBoolean(key, defValue);
}
}
@maxpinto
Copy link

SharedPreferenceLiveData should extends MutableLiveData?, or am i wrong?

@cuiyiming007
Copy link

SharedPreferenceLiveData should extends MutableLiveData?, or am i wrong?
You don not need extend MutableLiveData. setValue and postValue are protected, so you can use them as long as you extend LiveData.

@baggednismo
Copy link

How do you use this with Transformation switchmap? I would like to use it with my ViewModel and the ViewModel needs to be aware of changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment