SharedPreferences by DataStore with kotlinDataStore,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.
DataStore object:private val dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
private val switchStateKey = booleanPreferencesKey("toggle")
dataStore.data.map {
it[switchStateKey] ?: false
}.asLiveData().observe(this) {
Log.d(TAG, "getToggleSwitchState: $it")
binding.preferenceSwitch.isChecked = it
}
isChecked = !isChecked
lifecycleScope.launch {
val key = switchStateKey
dataStore.edit { preferences ->
preferences[key] = isChecked
}
}
it’s all of use
DataStorereplaceSharedPreferences.
Proto DataStorexx.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;
}
proto datastore structobject 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)
}
proto datastore object val Context.settingsDataStore: DataStore<ProtoCounter> by dataStore(
fileName = "settings.pb",
serializer = SettingsSerializer
)
proto datastore binding.protoCounter.setOnClickListener {
lifecycleScope.launch {
settingsDataStore.updateData { currentSettings ->
currentSettings.toBuilder()
.setExampleCounter(currentSettings.exampleCounter + 1)
.build()
}
}
}
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 …