Android Jetpack Preferences Datastore (SharedPreferences for Compose)

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.