DataStore is a new data storage solution in Android that provides a replacement for SharedPreferences. It allows you to store small amounts of key-value pairs or typed objects. DataStore is built on top of Kotlin Coroutines and Flow APIs, making it more efficient and easier to use for asynchronous data access.
Internally, DataStore uses a protobuf-based schema to serialize and deserialize data. It works with two types: Preferences DataStore, which stores key-value pairs, and Proto DataStore, which stores custom data types defined by a schema. The persistence is handled through a file-based system, ensuring data remains even after the app is closed.
DataStore provides a safe, consistent way to manage your app's data with built-in support for reactive programming. This means that when data changes, your UI can automatically update, which is a significant advantage over traditional SharedPreferences.
Here’s an example of how to use DataStore to save and retrieve user preferences:
// Create a Preferences DataStore
val dataStore: DataStore = context.createDataStore(name = "settings")
// Save data
suspend fun saveUserPreference(preferenceKey: String, preferenceValue: String) {
dataStore.edit { preferences ->
preferences[stringPreferencesKey(preferenceKey)] = preferenceValue
}
}
// Retrieve data
val userPreferenceFlow: Flow = dataStore.data
.map { preferences ->
preferences[stringPreferencesKey("your_preference_key")] ?: "default_value"
}
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?