I have a repository including a list of words which I connected with a unique checkbox. Each time I close the app I want the checkbox value to be saved. So I am using Jetpack DataStore for that. It saves properly but it does it for all the words and I wish it does it for each of them separately.
I know how to retrieve that when they are String but can't figure out when they are Boolean.
My Repository
object WordRepo {
fun getWord(wordId: String, context: Context): Words =
getWordsList(context).find { it.wordId == wordId }!!
fun getWordsList(context: Context) = listOf(
Words(
wordId = context.getString(R.string.a),
wordName = context.getString(R.string.a),
wordCheckBox = false
),
Words(
wordId = context.getString(R.string.cold),
wordName = context.getString(R.string.cold),
wordDone = false
),
Words(
wordId = context.getString(R.string.star),
wordName = context.getString(R.string.star),
wordCheckBox = false
),
)
}
My CheckBox
val scope = rememberCoroutineScope()
val dataStore = DataStore(context)
var checkBool by remember { mutableStateOf(value = word.wordCheckBox) }
Checkbox(
checked = checkBool,
onCheckedChange = {
checkBool = it
scope.launch { dataStore.saveBool(word.wordCheckBox) }
}
)
}
My DataStore
class DataStore(private val context: Context){
companion object {
val Context.dataStore:
DataStore<Preferences> by preferencesDataStore(name = "MyPreferences")
val BOOL = booleanPreferencesKey("checked")
}
val getBool: Flow<Boolean> = context.dataStore.data.map {
preferences -> preferences[BOOL]?: false }
suspend fun saveBool(value: Boolean) {
context.dataStore.edit { preferences-> preferences[BOOL] = value }
}
}
Aucun commentaire:
Enregistrer un commentaire