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.
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"
Next, create a DataStore instance.
import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.preferencesDataStore;
val Context.dataStore: DataStore by preferencesDataStore(name = "settings")
You'll need to define the keys to store your data.
import androidx.datastore.preferences.core.stringPreferencesKey
val EXAMPLE_KEY = stringPreferencesKey("example_key")
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
}
}
}
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]
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?