Edit module build.gradle
dependencies {
implementation("androidx.datastore:datastore-preferences:1.0.0")
}
Create AppSingleton.kt
import androidx.datastore.core.DataStoreimport androidx.datastore.dataStoreimport androidx.datastore.preferences.core.Preferencesimport androidx.datastore.preferences.preferencesDataStoreclass AppSingleton { companion object { val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") }}
Usage in sample compose screen.
@Composablefun HomeScreen( // viewModel: HomeViewModel = viewModel()) { val PREFERENCES_COUNTER = intPreferencesKey("counter") val PREFERENCES_USERNAME = stringPreferencesKey("userName") val preferences by context.dataStore.data.collectAsState(initial = null) val username: String = preferences?.get(PREFERENCES_USERNAME) ?: "" val counter: Int = preferences?.get(PPREFERENCES_COUNTER) ?: 0 suspend fun saveUsername(username: String) { context.dataStore.edit { settings -> settings[PREFERENCES_USERNAME] = username } } suspend fun incrementCounter() { context.dataStore.edit { settings -> settings[PREFERENCES_COUNTER] = counter + 1 } }}
References: