今天测试了一下google推荐使用的datastore
package com.xxx.xxx.datastore;
/**
* Created by easyboot.
* on Date: 2021/8/12 Time: 17:18
*/
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.datastore.preferences.core.MutablePreferences;
import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.core.PreferencesKeys;
import androidx.datastore.preferences.rxjava2.RxPreferenceDataStoreBuilder;
import androidx.datastore.rxjava2.RxDataStore;
import io.reactivex.Flowable;
import io.reactivex.Single;
public class MyDataStore {
private static final String TAG = MyDataStore.class.getSimpleName();
//保存在磁盘上的DataStore文件名称
private static final String MY_DATA_STORE_NAME = "MyData.pb";
private Context mContext;
//数据存储对象
private RxDataStore<Preferences> mDataStore;
//使用单例来访问本类
private static MyDataStore INSTANCE;
private MyDataStore(Context context) {
if (context == null) {
throw new RuntimeException("Application context cannot be null");
}
mContext = context.getApplicationContext();
//创建数据存储对象
mDataStore = new RxPreferenceDataStoreBuilder(mContext, MY_DATA_STORE_NAME).build();
}
public static MyDataStore getInstance(@NonNull Context context) {
if (INSTANCE == null) {
synchronized (MyDataStore.class) {
if (INSTANCE == null) {
INSTANCE = new MyDataStore(context);
}
}
}
return INSTANCE;
}
//从DataStore中查询键对应的值
public String getDataValue(String key) {
Preferences.Key<String> DATA_ID = PreferencesKeys.stringKey(key);
Flowable<String> carIdFlow = mDataStore.data().map(prefs -> prefs.get(DATA_ID));
try {
//同步等待返回值
return carIdFlow.blockingFirst();
} catch (Exception e) {
//查询不到默认返回null
return null;
}
}
//为DataStore中的键设置新的值
public void setDataValue(String key,String dataValue) {
Preferences.Key<String> DATA_ID = PreferencesKeys.stringKey(key);
Single<Preferences> setResult = mDataStore.updateDataAsync(preferences -> {
MutablePreferences mutablePreferences = preferences.toMutablePreferences();
String oldValue = preferences.get(DATA_ID);
mutablePreferences.set(DATA_ID, dataValue);
return Single.just(mutablePreferences);
});
}
}
本文介绍了如何在Android应用中使用Google推荐的DataStore进行数据持久化操作。通过示例展示了如何创建和使用RxDataStore实例,以及如何读取和更新数据。DataStore是Android Jetpack库的一部分,提供了更安全、高效的偏好设置存储方式。
1909

被折叠的 条评论
为什么被折叠?



