美文网首页
你好JetPack--->DataStore!

你好JetPack--->DataStore!

作者: JetBrains_ | 来源:发表于2020-12-03 15:36 被阅读0次

DataStore 提供了两种存储方案 Preferences DataStoreProto DataStore
根据官网的介绍大概含义为:
Preferences DataStore 使用键值存储访问数据此实现不需要预定义的架构(类型不安全性)
Proto DataStore 将数据存储为自定义数据类型的实例,此实现要求使用协议缓冲区定义架构(类型安全性)

下面先来介绍一下Preferences DataStore的使用

所需添加的依赖库:

dependencies {
    // Preferences DataStore
    implementation "androidx.datastore:datastore-preferences:1.0.0-alpha02"
    // Proto DataStore
    implementation "androidx.datastore:datastore-core:1.0.0-alpha02"
}

Preferences DataStore支持的类型数据有Int,String,Boolean,Float,Long,Set
源码:

inline fun <reified T : Any> preferencesKey(name: String): Preferences.Key<T> {
    return when (T::class) {
        Int::class -> {
            Preferences.Key<T>(name)
        }
        String::class -> {
            Preferences.Key<T>(name)
        }
        Boolean::class -> {
            Preferences.Key<T>(name)
        }
        Float::class -> {
            Preferences.Key<T>(name)
        }
        Long::class -> {
            Preferences.Key<T>(name)
        }
        Set::class -> {
            throw IllegalArgumentException("Use `preferencesSetKey` to create keys for Sets.")
        }
        else -> {
            throw IllegalArgumentException("Type not supported: ${T::class.java}")
        }
    }
}

首先我们需要先声明一个DataStore,代码如下

// name 是你存储到内存卡里DataStore的文件名称
private val dataStore: DataStore<Preferences> by lazy {
        context.createDataStore(name = name)
}

定义一个key

//key是存取数据的标示,与prefrence里边的key差不多一个意思
val key = preferencesKey<Int>(name = key)

存入数据直接调用DataStore的扩展函数edit

// value 是你要存的值
dataStore.edit { preferences ->
    preferences[key] = value
}

读取数据,用到了Kotlin 协程的 Flow

val key = preferencesKey<Int>(name = key)
val value:Int = dataStore.data.map { preferences ->
    preferences[key] ?: 0
}.first()

完整的代码示例:

class DataStoreUtils constructor(context: Context, name: String) {
    private val dataStore: DataStore<Preferences> by lazy {
        context.createDataStore(name = name)
    }

    suspend fun setIntValue(key: String, value: Int) {
        val key = preferencesKey<Int>(name = key)
        dataStore.edit { preferences ->
            preferences[key] = value
        }
    }

    suspend fun getIntValue(key: String): Int {
        val key = preferencesKey<Int>(name = key)
        return dataStore.data.map { preferences ->
            preferences[key] ?: 0
        }.first()
    }


    suspend fun setStringValue(key: String, value: String) {
        val key = preferencesKey<String>(name = key)
        dataStore.edit { preferences ->
            preferences[key] = value
        }
    }

     suspend fun getStringValue(key: String): String {
        val key = preferencesKey<String>(name = key)
         return dataStore.data.map { preferences ->
             preferences[key] ?: ""
         }.first()
    }

    suspend fun setBooleanValue(key: String, value: Boolean) {
        val key = preferencesKey<Boolean>(name = key)
        dataStore.edit { preferences ->
            preferences[key] = value
        }
    }

    suspend fun getBooleanValue(key: String): Boolean {
        val key = preferencesKey<Boolean>(name = key)
        return dataStore.data.map { preferences ->
            preferences[key] ?: false
        }.first()
    }

    suspend fun setFloatValue(key: String, value: Float) {
        val key = preferencesKey<Float>(name = key)
        dataStore.edit { preferences ->
            preferences[key] = value
        }
    }

    suspend fun getFloatValue(key: String): Float {
        val key = preferencesKey<Float>(name = key)
        return dataStore.data.map { preferences ->
            preferences[key] ?: 0f
        }.first()
    }

    suspend fun setLongValue(key: String, value: Long) {
        val key = preferencesKey<Long>(name = key)
        dataStore.edit { preferences ->
            preferences[key] = value
        }
    }

    suspend fun getLongValue(key: String): Long {
        val key = preferencesKey<Long>(name = key)
        return dataStore.data.map { preferences ->
            preferences[key] ?: 0L
        }.first()
    }
}
class MainActivity : AppCompatActivity() {

    private val dataStoreUtils: DataStoreUtils by lazy {
        DataStoreUtils(this, DataStoreConst.DATA_STORE_NAME)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_write.setOnClickListener {
            lifecycleScope.launch {
                dataStoreUtils.setIntValue(DataStoreConst.DATA_STORE_INT_KEY, 1024)
                dataStoreUtils.setStringValue(DataStoreConst.DATA_STORE_STRING_KEY, "1024")
                dataStoreUtils.setBooleanValue(DataStoreConst.DATA_STORE_BOOLEAN_KEY, true)
                dataStoreUtils.setFloatValue(DataStoreConst.DATA_STORE_FLOAT_KEY, 1024f)
                dataStoreUtils.setLongValue(DataStoreConst.DATA_STORE_LONG_KEY, 1024L)
            }
        }

        btn_read.setOnClickListener {
            lifecycleScope.launch {
                val intValue = dataStoreUtils.getIntValue(DataStoreConst.DATA_STORE_INT_KEY)
                val stringValue = dataStoreUtils.getStringValue(DataStoreConst.DATA_STORE_STRING_KEY)
                val booleanValue = dataStoreUtils.getBooleanValue(DataStoreConst.DATA_STORE_BOOLEAN_KEY)
                val floatValue = dataStoreUtils.getFloatValue(DataStoreConst.DATA_STORE_FLOAT_KEY)
                val longValue = dataStoreUtils.getLongValue(DataStoreConst.DATA_STORE_LONG_KEY)
                Log.d("TAG", "DataStore: IntValue:$intValue , StringValue:$stringValue " +
                        ",BooleanValue:$booleanValue ,FloatValue:$floatValue ,LongValue:$longValue")
            }
        }

    }
}

参考文献
JetPack DataSotre 官方文档

相关文章

网友评论

      本文标题:你好JetPack--->DataStore!

      本文链接:https://www.haomeiwen.com/subject/hnemwktx.html