Home > Software engineering >  Read value from DataStore with flow before updating it
Read value from DataStore with flow before updating it

Time:08-14

I'm quite new using Kotlin's flows and Jetpack's DataStore. But I'm writing a list of custom objects (serialized as a JSON) which I want to update before inserting a new value.

Therefore when wanting to insert a new element, previously I have to read the current value, therefore I'm collecting the values from the flow, adding the new one and then writing on the DataStore. The issue is that once the DataStorehas finished writing the values I receive a new event from the flow I got subscribe, therefore I'm in a loop writing the values.

My question is, is there any way to collecting the values from the flow just once or cancel the flowafter I've read the values, or is there a better way to manage this situation with DataStore?

CodePudding user response:

Yes you can get only data from datastore like this

   // This function belongs on your datastore file
   suspend fun getMyCustomData(): String {
        val preferences = dataStore.data.first()
        return preferences[MY_CUSTOM_KEY] ?: ""
   }

And after reading the value you can update your object without getting stuck in a loop.

  • Related