android: Preferences DataStore 和 Proto DataStore use guide

replace SharedPreferences by DataStore<Preferences> with kotlin

in Datastore Doc, it provide two way to use DataStore<Preferences>,

user can use kotlin or java language to implement it. But in fact, use java to implement it will be very different.
Maybe you can use Rxjava to simplify it, but in fact, use Rxjava to implement it is also not easy.
use kotlin will very simple to implement it? yes. and it’s ONLY ONE WAY to use it by kotlin.

steps
  1. init DataStore<Preferences> object:
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
    private val switchStateKey = booleanPreferencesKey("toggle")
    
  2. get value from defined key:
        dataStore.data.map {
            it[switchStateKey] ?: false
        }.asLiveData().observe(this) {
            Log.d(TAG, "getToggleSwitchState: $it")
            binding.preferenceSwitch.isChecked = it
        }
    
  3. set value to defined key:
    isChecked = !isChecked
    lifecycleScope.launch {
        val key = switchStateKey
        dataStore.edit { preferences ->
            preferences[key] = isChecked
        }
    }
    

it’s all of use DataStore<Preferences> replace SharedPreferences.

use Proto DataStore

steps:
  1. define xx.proto file (path: [module]/src/main/proto/xxx.proto)
    syntax = "proto3";
    
    option java_package = "com.example.application";
    option java_multiple_files = true;
    
    message ProtoCounter {
       int32 example_counter = 1;
    }
    
  2. define proto datastore struct
    object SettingsSerializer : Serializer<ProtoCounter> {
       override val defaultValue: ProtoCounter = ProtoCounter.getDefaultInstance()
    
        override suspend fun readFrom(input: InputStream): ProtoCounter {
            try {
                return ProtoCounter.parseFrom(input)
            } catch (exception: InvalidProtocolBufferException) {
                throw CorruptionException("Cannot read proto.", exception)
            }
        }
       
        override suspend fun writeTo(
            t: ProtoCounter,
            output: OutputStream
        ) = t.writeTo(output)
    }
    
  3. init proto datastore object
       val Context.settingsDataStore: DataStore<ProtoCounter> by dataStore(
            fileName = "settings.pb",
            serializer = SettingsSerializer
       )
    
  4. set value to proto datastore
         binding.protoCounter.setOnClickListener {
             lifecycleScope.launch {
                 settingsDataStore.updateData { currentSettings ->
                     currentSettings.toBuilder()
                         .setExampleCounter(currentSettings.exampleCounter + 1)
                         .build()
                 }
             }
         }
    
  5. get value from proto datastore
         settingsDataStore.data
             .map { settings ->
                 // The exampleCounter property is generated from the proto schema.
                 settings.exampleCounter
             }.asLiveData().observe(this) {
                 it?.let {
                     binding.protoCounter.text = getString(R.string.proto_counter_text, it)
                 }
             }
    

it’s all of use Proto DataStore.

can not use a chinese input method, so …

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值