Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper instance creation of Android's Jetpack DataStore (alpha07 version)

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.

like image 406
Borna Ungar Avatar asked Mar 03 '21 23:03

Borna Ungar


1 Answers

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,
)
like image 93
Alex P Avatar answered Oct 06 '22 15:10

Alex P