Created
August 29, 2022 10:49
-
-
Save cp-hardik-p/05e36ad7abb3e2e578c7bad8665e17a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SaveUserInfo(private val context: Context) { | |
// Create the dataStore and give it a name same as user_pref | |
// Create some keys we will use them to store and retrieve the data | |
companion object { | |
val Context.dataStore: DataStore<Preferences> by preferencesDataStore("user_prefs") | |
val USER_AGE_KEY = intPreferencesKey("USER_AGE") | |
val USER_NAME_KEY = stringPreferencesKey("USER_NAME") | |
} | |
// Store user data | |
// refer to the data store and using edit | |
// we can store values using the keys | |
suspend fun storeUserInfo(age: Int, name: String) { | |
context.dataStore.edit { preferences -> | |
preferences[USER_AGE_KEY] = age | |
preferences[USER_NAME_KEY] = name | |
} | |
} | |
// get the user's age | |
val userAgeFlow: Flow<Int> = context.dataStore.data.map { preferences -> | |
preferences[USER_AGE_KEY] ?: 0 | |
} | |
// get the user's name | |
val userNameFlow: Flow<String> = context.dataStore.data.map { preferences -> | |
preferences[USER_NAME_KEY] ?: "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment