@@ -25,10 +25,59 @@ import androidx.compose.runtime.remember
2525import androidx.compose.runtime.setValue
2626import androidx.compose.ui.Alignment
2727import androidx.compose.ui.Modifier
28+ import androidx.compose.ui.platform.LocalContext
2829import androidx.compose.ui.text.input.KeyboardType
2930import androidx.compose.ui.unit.dp
3031import androidx.core.text.isDigitsOnly
3132
33+ @Composable
34+ fun rememberDataStoreStringState (
35+ key : androidx.datastore.preferences.core.Preferences .Key <String >,
36+ defaultValue : String
37+ ): MutableState <String > {
38+ val context = LocalContext .current
39+ val dataStore = context.dataStore
40+ val coroutineScope = rememberCoroutineScope()
41+
42+ val savedFlow = remember(key) {
43+ dataStore.data.map { preferences ->
44+ preferences[key] ? : defaultValue
45+ }
46+ }
47+ val savedValue = savedFlow.collectAsState(initial = defaultValue).value
48+
49+ val state = remember {
50+ mutableStateOf(savedValue)
51+ }
52+
53+ LaunchedEffect (savedValue) {
54+ if (state.value != savedValue) {
55+ state.value = savedValue
56+ }
57+ }
58+
59+ return remember {
60+ object : MutableState <String > {
61+ override var value: String
62+ get() = state.value
63+ set(newValue) {
64+ if (state.value != newValue) {
65+ state.value = newValue
66+
67+ coroutineScope.launch {
68+ dataStore.edit { preferences ->
69+ preferences[key] = newValue
70+ }
71+ }
72+ }
73+ }
74+
75+ override fun component1 () = value
76+ override fun component2 (): (String ) -> Unit = { value = it }
77+ }
78+ }
79+ }
80+
3281@Composable
3382fun OptionBase (
3483 title : String ,
0 commit comments