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
- init
DataStore<Preferences>object:private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") private val switchStateKey = booleanPreferencesKey("toggle") - get value from defined key:
dataStore.data.map { it[switchStateKey]

本文介绍如何使用DataStore<Preferences>替代SharedPreferences进行数据存储。通过Kotlin实现DataStore的初始化、读取及更新操作,并展示了使用ProtoDataStore处理复杂数据结构的方法。
最低0.47元/天 解锁文章
143

被折叠的 条评论
为什么被折叠?



