//创建sharedPreference实例
SharedPreferences mySP = getApplicationContext().getSharedPreferences("rx_sp_test", Context.MODE_PRIVATE);
mySP.edit().putString("test_string","this is test rx string").commit();
mySP.edit().putBoolean("test_boolean",true).commit();
//将sharedPreference作为参数转换成RxSharedPreferences实例
RxSharedPreferences rxPreferences = RxSharedPreferences.create(mySP);
//获取保存的值
Preference<String> testString = rxPreferences.getString("test_string");
Preference<Boolean> testBoolean = rxPreferences.getBoolean("test_boolean", false);
//发射数据
testString.asObservable()
.subscribe(new Action1<String>() {
@Override
public void call(String username) {
Log.e(TAG, "test_string: " + username);
}
});
testBoolean.asObservable()
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
Log.e(TAG, "test_boolean: " + aBoolean);
}
});
运行结果:
注:1.需要在build.gradle中添加compile 'com.f2prateek.rx.preferences:rx-preferences:1.0.2'
2.参考资料:https://github.com/ReactiveX/RxAndroid/wiki#removed
https://github.com/f2prateek/rx-preferences