Kotlin DataStore
- apply dependencies
implementation "androidx.datastore:datastore-preferences:$latestversion"
- create instance prefrences data store
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
- define preferences datastore key word
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
- get value from preferences datastore
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[EXAMPLE_COUNTER] ?: 0
}
- saving value
suspend fun incrementCounter() {
context.dataStore.edit { settings ->
// get value
val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
// edit value
settings[EXAMPLE_COUNTER] = currentCounterValue + 1
}
}
Komentar
Posting Komentar