How to use DataStore in an Android app?

DataStore is a Jetpack library that provides a type-safe and protocol buffer-based way to store key-value pairs in an Android application. It serves as a more efficient and easier alternative to SharedPreferences. In this guide, we will walk through the steps to implement DataStore in your Android app.

Step 1: Add Dependencies

First, add the necessary dependencies in your app-level build.gradle file.

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

Step 2: Create DataStore

Next, create a DataStore instance.

import androidx.datastore.preferences.core.Preferences; import androidx.datastore.preferences.preferencesDataStore; val Context.dataStore: DataStore by preferencesDataStore(name = "settings")

Step 3: Define Keys

You'll need to define the keys to store your data.

import androidx.datastore.preferences.core.stringPreferencesKey val EXAMPLE_KEY = stringPreferencesKey("example_key")

Step 4: Store Data

Now let's write a function to store data in the DataStore.

import kotlinx.coroutines.runBlocking fun saveData(context: Context, value: String) { runBlocking { context.dataStore.edit { preferences -> preferences[EXAMPLE_KEY] = value } } }

Step 5: Read Data

Finally, we can read the data from our DataStore.

import kotlinx.coroutines.flow.first suspend fun readData(context: Context): String? { val preferences = context.dataStore.data.first() return preferences[EXAMPLE_KEY] }

DataStore Android DataStore Android Jetpack SharedPreferences alternative key-value storage