implementation("androidx.datastore:datastore-preferences:1.1.1")
package com.example.myapplication
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import com.example.myapplication.databinding.TestDsBinding
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class DsDemo : AppCompatActivity() {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
private val keyName = stringPreferencesKey("name")
private val ageName = intPreferencesKey("age")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val inflate = TestDsBinding.inflate(layoutInflater)
setContentView(inflate.root)
inflate.btnSave.setOnClickListener {
lifecycleScope.launch {
dataStore.edit {
it[keyName] = "王祥林"
it[ageName] = 18
}
}
}
inflate.btnRead.setOnClickListener {
lifecycleScope.launch {
val nameFlow = dataStore.data.map {
it[keyName]
}
nameFlow.collect { name ->
println(name)
}
val ageFlow = dataStore.data.map {
it[ageName]
}
ageFlow.collect { age ->
println(age)
}
val muxFlow = dataStore.data.map {
println("name==>" + it[ageName])
println("age===>" + it[keyName])
}
println(muxFlow)
}
}
}
}