Sobes.tech
Junior

Have you worked with DataStore Preferences in Android?

sobes.tech AI

Answer from AI

Yes, I have worked with it.

DataStore Preferences is an asynchronous counterpart to SharedPreferences, part of AndroidX DataStore. It allows safe storage of simple key-value pairs using KSP over Kotlin Flow or RxJava3 for asynchronous operations and Protobuf/Proto DataStore or Proto DataStore for data types.

Main advantages of DataStore Preferences compared to SharedPreferences:

  • Asynchronous: Works with Flow or RxJava3, preventing main thread blocking and avoiding ANR issues.
  • Safety: Atomic read/write operations ensure data consistency.
  • Type safety: With Protobuf DataStore, you can define a data schema, preventing errors with data types.
  • Reactivity: Allows observing data changes in real-time.

Example of using DataStore Preferences with Kotlin Flow:

// Creating DataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

// Reading data
suspend fun readString(context: Context, key: String): String? {
    val preferencesKey = stringPreferencesKey(key)
    val preferences = context.dataStore.data.first()
    return preferences[preferencesKey]
}

// Writing data
suspend fun writeString(context: Context, key: String, value: String) {
    val preferencesKey = stringPreferencesKey(key)
    context.dataStore.edit { settings ->
        settings[preferencesKey] = value
    }
}

Example of using KSP for type-safe access:

// Add plugin in build.gradle (:app)
plugins {
 ...
 id("com.google.devtools.ksp") version "1.7.21-1.0.8" // Example version, check for latest
}

// Add dependencies in build.gradle (:app)
dependencies {
 ...
 implementation("androidx.datastore:datastore-preferences:1.0.0") // Check for latest version
 implementation("androidx.datastore:datastore-preferences-core:1.0.0") // Check for latest version
 ksp("androidx.datastore:datastore-preferences-core:1.0.0") // Check for latest version
}

// Define interface for KSP
interface SettingsPref {
    val appName: String
    val isNotificationsEnabled: Boolean
    val theme: Int
}

// Generate implementation using KSP
// Will create a class like SettingsPrefImpl, which can be used to access data

DataStore Preferences is the recommended way to store simple settings and data in Android, replacing the deprecated SharedPreferences.