androiddatastore-preferences:Propertydelegate必须拥有'getValue(Context,KProperty<*>)'方法
创始人
2024-10-07 03:00:40
0

在自定义的 Property delegate 中添加 'getValue(Context, KProperty<*>)' 方法即可。例如,以下是一个名为 StringPreference 的 Property delegate 的示例代码:

import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore

private val Context.dataStore by preferencesDataStore("data_store")

class StringPreference(private val key: String) {

    operator fun getValue(context: Context, property: KProperty<*>): String {
        val preferencesKey = stringPreferencesKey(key)
        val dataStore = context.dataStore
        val valueFlow = dataStore.data.map { preferences ->
            preferences[preferencesKey] ?: ""
        }
        return runBlocking { valueFlow.first() }
    }

    operator fun setValue(context: Context, property: KProperty<*>, value: String) {
        val preferencesKey = stringPreferencesKey(key)
        val dataStore = context.dataStore
        runBlocking {
            dataStore.edit { preferences ->
                preferences[preferencesKey] = value
            }
        }
    }
}

使用示例:

class MainActivity : AppCompatActivity() {
    private val stringPreference by lazy { StringPreference("key_name") }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val value = stringPreference.getValue(this, ::stringPreference)
        Log.d("StringPreferenceTest", "Value: $value")
        stringPreference.setValue(this, ::stringPreference, "NewValue")
    }
}

相关内容

热门资讯

透视辅助!德普之星透视免费(透... 透视辅助!德普之星透视免费(透视)真是存在有挂(详细辅助wpk教程);1、每一步都需要思考,不同水平...
最新研发!wepoker有用吗... 最新研发!wepoker有用吗,wepoker免费脚本,细节揭秘(有挂教程);原来确实真的有挂(需添...
玩家必看科普!wejoker辅... 玩家必看科普!wejoker辅助软件价格,wepoker底牌透视脚本,力荐教程(有挂技巧)是由北京得...
透视辅助!pokemomo辅助... 透视辅助!pokemomo辅助工具(透视)一贯有挂(详细辅助必胜教程);1、很好的工具软件,可以解锁...
热点推荐!wepoker-h5... 热点推荐!wepoker-h5下载,wejoker辅助软件价格,可靠教程(有挂教程);科技安装教程;...
透视新版!wpk插件(透视)确... 透视新版!wpk插件(透视)确实真的是有挂(详细辅助wepoke教程)1、机器人多个强度级别选择2、...
今日百科!wepoker辅助器... 1、今日百科!wepoker辅助器下载,wepoker透视器免费,解密教程(有挂神器)。2、wepo...
透视挂透视!德普之星透视辅助软... 透视挂透视!德普之星透视辅助软件激活码(透视)都是是真的有挂(详细辅助黑科技教程)在进入德普之星透视...
一分钟揭秘!we poker辅... 一分钟揭秘!we poker辅助器v3.3,aapoker透视脚本入口,教你教程(有挂教程)1、点击...
透视ai代打!破解辅助插件we... 透视ai代打!破解辅助插件wepoker(透视)其实是有挂(详细辅助线上教程);辅助器中分为三种模型...