简体   繁体   中英

Read value from DataStore with flow before updating it

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 DataStore has 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 flow after I've read the values, or is there a better way to manage this situation with DataStore ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM