• Shared Preferences
• Just a XML based KVS
• boolean,String,float,int,long,Set
• Tend to be messy to manage keys
Slide 3
Slide 3 text
public class PreferenceManager {
private static final String KEY_USER_ID = "user_id";
public putUserId(int userId) {
prefs.edit().putInt(KEY_USER_ID, userId).apply();
}
public int getUserId() {
return prefs.getUserId(KEY_USER_ID, -1);
}
public boolean hasUserId() {
return prefs.contains(KEY_USER_ID);
}
public void removeUserId() {
prefs.edit().remove(KEY_USER_ID).apply();
}
}
Slide 4
Slide 4 text
private static final String SHARED_PREFS_NAME = "HogeActivity";
private static final String LAST_UPDATE_TICK_KEY = "lastUpdateTick";
private static final String LAST_DAILY_TASK_TICK_KEY = "lastDailyTaskTick";
private static final String LAST_SPLASH_EVENT_KEY = "lastSplashEventTick";
private static final String FCM_TOKEN_KEY = "fcmToken";
private static final String GCM_REGISTRATION_ID_KEY = "gcmRegistrationId";
private static final String GCM_APP_VERSION_KEY = "gcmAppVersion";
private static final String INVALIDATED_COUNT_KEY = "invalidatedCount";
private static final String LAUNCH_COUNT_KEY = "launchCount";
private static final String FIRST_BOOT_TICK_KEY = "firstBootTick";
private static final String RATING_DIALOG_KEY = "ratingDialogKey";
Slide 5
Slide 5 text
• Rx and Preferences
• Deal with every “data” as Observable
• We need a subscription mechanism
• Yes, RxJava!
• Compound with other Rx libraries
@Pref("sample")
class Sample {
@Key(name = "long_value")
long longValue = false;
// you can define default value like stringValue
@Key(name = "string_value")
String stringValue = "default_value";
@Key(name = "boolean_value")
boolean booleanValue;
@Key(name = "int_value")
int intValue;
@Key(name = "float_value")
float floatValue;
@Key(name = "set_string")
Set setStringValue;
}
Define a model
// as primitive
boolean value = preferences.getBooleanValue().asValue();
// as Observable
Observable value =
preferences.getBooleanValue().asObservable();
// as Action
Action1 super Boolean> value =
preferences.getBooleanValue().asAction();
As RxJava
Slide 15
Slide 15 text
subscriptions.add(preference.asObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(RxCompoundButton.checked(checkBox)));
subscriptions.add(RxCompoundButton.checkedChanges(checkBox)
.skip(1)
.subscribe(preference.asAction()));
With Rx libraries