Skip to content

Instantly share code, notes, and snippets.

@mgp
Last active August 29, 2015 14:27
Show Gist options
  • Save mgp/f75d4c69006c029eb6f3 to your computer and use it in GitHub Desktop.
Save mgp/f75d4c69006c029eb6f3 to your computer and use it in GitHub Desktop.
package org.khanacademy.android.prefs;
import org.khanacademy.core.util.ObservableUtils;
import rx.Observable;
import rx.subjects.PublishSubject;
import android.content.SharedPreferences;
/**
* Lightweight, internal preferences.
*/
public class InternalPreferences {
/** The underlying preferences store in the system. */
private final SharedPreferences mSharedPreferences;
private PublishSubject<BooleanPreference> mUpdatedBooleanPreferenceSubject;
public InternalPreferences(SharedPreferences sharedPreferences) {
mSharedPreferences = sharedPreferences;
mUpdatedBooleanPreferenceSubject = PublishSubject.create();
}
public boolean hasSet(OneTimeMarkerPreference pref) {
return mSharedPreferences.getBoolean(pref.getKey(), false);
}
public boolean markIfUnset(OneTimeMarkerPreference pref) {
if (!hasSet(pref)) {
mSharedPreferences.edit().putBoolean(pref.getKey(), true).apply();
return true;
}
return false;
}
public boolean getValue(BooleanPreference pref) {
return mSharedPreferences.getBoolean(pref.getKey(), pref.getDefaultValue());
}
public Observable<Boolean> observeValue(final BooleanPreference pref) {
return ObservableUtils.cache(
mUpdatedBooleanPreferenceSubject
.filter(updatedPref -> updatedPref.getKey().equals(pref.getKey()))
.map(unused -> getValue(pref))
.distinctUntilChanged(),
1
);
}
public void setValue(BooleanPreference pref, boolean value) {
mSharedPreferences.edit().putBoolean(pref.getKey(), value).apply();
mUpdatedBooleanPreferenceSubject.onNext(pref);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment