Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rx and Preferences

@hotchemi
November 24, 2016

Rx and Preferences

@hotchemi

November 24, 2016
Tweet

More Decks by @hotchemi

Other Decks in Programming

Transcript

  1. • Shared Preferences • Just a XML based KVS •

    boolean,String,float,int,long,Set<String> • Tend to be messy to manage keys
  2. 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();
 }
 }
  3. 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";
  4. • Rx and Preferences • Deal with every “data” as

    Observable • We need a subscription mechanism • Yes, RxJava! • Compound with other Rx libraries
  5. @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<String> setStringValue;
 } Define a model
  6. // as primitive boolean value = preferences.getBooleanValue().asValue(); // as Observable

    Observable<Boolean> value = preferences.getBooleanValue().asObservable(); // as Action Action1<? super Boolean> value = preferences.getBooleanValue().asAction(); As RxJava