Store Key Value Pairs Using Jetpack Data Store

One of the ways we can store information on an Android device is by using Shared Preferences. These Shared Preferences help us save key-value pairs. A newer way of saving such key-value pairs is using the Jetpack library Data Store.

The Data Store library saves the key-value pairs using coroutine blocks and provides the ability to read the saved preferences using the collect function available in the Kotlin Flow.

In this article, we will take a look at the Data Store class available in the Jetpack library and how to save, read the data using it.

The first thing we need to do is add the dependency in the module level build.gradle file.

implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"

Create an instance of the Data Store using context and by passing the file name to the createDataStore function. Android creates the data store file inside a folder named datastore and this folder will be available in the app's files directory. The name passed to the createDataStore method is used as the file name.

/**
 * Create a data store preference
 */
private val store = context.createDataStore(PREF_FILE_NAME_ACCOUNT)
Before we start using the created datastore variable to save the data or read the data, we need to create a preference key that can hold a value.
/**
 * String preference key that contains the name
 */
private val nameKey = stringPreferencesKey(PREF_ACCOUNT_NAME)
Since the nameKey is a string preference key, it can be used to hold the string values. Similarly, if we want to save boolean value, we need to use booleanPreferencesKey, intPreferencesKey to save integers and more.

Call edit function to start editing the preferences. Then update the value using the created preference key. This will save the data specified with the preference name in the preference file.
/**
 * Save the name in the preference
 */
suspend fun saveName(name: String) {
    // Edit the preferences
    store.edit {
        // Update the name
        it[nameKey] = name
    }
}
The data variable of the Data Store class exposes the values stored as a Kotlin Flow. Since Flow is returned, we need to use the collect function to continuously collect the values emitted.
/**
 * Get the name saved in the preference
 */
fun getName(): Flow<String> {
    return store.data.map {
        it[nameKey] ?: ""
    }
}
We can have these functions in a wrapper class and start using the functions to save the data and read the data as shown below.
// Create the preference class instance
val accountPref = AccountPref(context)
// Save the name in preferences
accountPref.saveName("gSrikar")
// Read the name from preference
accountPref.getName().collect {
    if(DBG) Log.d(TAG, "Saved Name: $it")
}
One thing to remember when using the collect function is that it should not be called directly in the Activity/Fragment. Unlike Live Data, collect function emits data even when the UI is not visible to the user. So, this may cause crashes when we are updating the UI inside it.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

How to Change Material Chip Text Size, Text Style and Font

Create Assets Folder, Add Files and Read Data From It

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment