jetpack之datastore

本文介绍了如何在Android应用中使用Google推荐的DataStore进行数据持久化操作。通过示例展示了如何创建和使用RxDataStore实例,以及如何读取和更新数据。DataStore是Android Jetpack库的一部分,提供了更安全、高效的偏好设置存储方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天测试了一下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);
        });
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值