DataStore封装代码

74 阅读1分钟

DataStoreManager 工具类,扩展支持常用的数据类型(如 IntBooleanFloatLong 等)

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException

// 扩展属性,用于获取 DataStore 实例
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_data_store")

class DataStoreManager(private val context: Context) {

    // 保存字符串类型的数据
    suspend fun saveString(key: String, value: String) {
        val preferencesKey = stringPreferencesKey(key)
        context.dataStore.edit { preferences ->
            preferences[preferencesKey] = value
        }
    }

    // 读取字符串类型的数据
    fun getString(key: String, defaultValue: String = ""): Flow<String> {
        return readPreference(stringPreferencesKey(key), defaultValue)
    }

    // 保存整数类型的数据
    suspend fun saveInt(key: String, value: Int) {
        val preferencesKey = intPreferencesKey(key)
        context.dataStore.edit { preferences ->
            preferences[preferencesKey] = value
        }
    }

    // 读取整数类型的数据
    fun getInt(key: String, defaultValue: Int = 0): Flow<Int> {
        return readPreference(intPreferencesKey(key), defaultValue)
    }

    // 保存布尔类型的数据
    suspend fun saveBoolean(key: String, value: Boolean) {
        val preferencesKey = booleanPreferencesKey(key)
        context.dataStore.edit { preferences ->
            preferences[preferencesKey] = value
        }
    }

    // 读取布尔类型的数据
    fun getBoolean(key: String, defaultValue: Boolean = false): Flow<Boolean> {
        return readPreference(booleanPreferencesKey(key), defaultValue)
    }

    // 保存浮点类型的数据
    suspend fun saveFloat(key: String, value: Float) {
        val preferencesKey = floatPreferencesKey(key)
        context.dataStore.edit { preferences ->
            preferences[preferencesKey] = value
        }
    }

    // 读取浮点类型的数据
    fun getFloat(key: String, defaultValue: Float = 0f): Flow<Float> {
        return readPreference(floatPreferencesKey(key), defaultValue)
    }

    // 保存长整型类型的数据
    suspend fun saveLong(key: String, value: Long) {
        val preferencesKey = longPreferencesKey(key)
        context.dataStore.edit { preferences ->
            preferences[preferencesKey] = value
        }
    }

    // 读取长整型类型的数据
    fun getLong(key: String, defaultValue: Long = 0L): Flow<Long> {
        return readPreference(longPreferencesKey(key), defaultValue)
    }

    // 删除指定键的数据
    suspend fun deleteKey(key: String) {
        context.dataStore.edit { preferences ->
            preferences.keys.forEach { preferenceKey ->
                if (preferenceKey.name == key) {
                    preferences.remove(preferenceKey)
                }
            }
        }
    }

    // 清空所有数据
    suspend fun clearAll() {
        context.dataStore.edit { preferences ->
            preferences.clear()
        }
    }

    // 通用的读取方法
    private fun <T> readPreference(key: Preferences.Key<T>, defaultValue: T): Flow<T> {
        return context.dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                preferences[key] ?: defaultValue
            }
    }
}