So with the new alpha07 version, Android ditched the private val dataStore = context.createDataStore(name = "settings_pref")
, however the new way they use datastore doesn't work for me.
Since upgrading from "androidx.datastore:datastore-core:1.0.0-alpha06" to alpha07, I can't seem to make my datastore syntax work without getting red-colored code (the error comes when i add context.dataStore.edit). Also downgrading back to alpha06, code that previously worked is now not working anymore (with createDataStore).
What I'm using is their example on the main page but going anywhere else they still haven't updated their examples besides this one.
@Singleton
class PreferencesManager @Inject constructor(@ApplicationContext context: Context) {
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
val exampleCounterFlow: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[EXAMPLE_COUNTER] ?: 0
}
suspend fun incrementCounter() {
context.dataStore.edit { settings ->
val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
settings[EXAMPLE_COUNTER] = currentCounterValue + 1
}
}
}
If someone knows the problem (or my error), I would appreciate it.
This was throwing me too, but I figured it out (aka, guessed until it worked):
// Note: This is at the top level of the file, outside of any classes.
private val Context.dataStore by preferencesDataStore("user_preferences")
class UserPreferencesManager(context: Context) {
private val dataStore = context.dataStore
// ...
}
This is for a DataStore<Preferences>
, but if you need a custom serializer, you can do the following (same parameters as the old method):
// Still top level!
private val Context.dataStore by dataStore(
fileName = "user_preferences",
serializer = MyCustomSerializer,
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With