Ooooh! I think I've got an android + kotlin questi...
# android
c
Ooooh! I think I've got an android + kotlin question 🤯 Okay. so here it goes. I'm using dataStore and I want to write a value... but I essentially want to write the value, but increment by 1 of the current value (or 0) Would this be the idiomatic way to do it? I guess to me it just seems wrong that I have to read it... and then use
first()
. It just looks smelly. Should I just be collecting the flow, and once the first item comes back then update with dataStore.edit?
Copy code
val current = dataStore.data.map { d -> d[count] ?: 0L }.first()
dataStore.edit { d -> d[count] = current + 1 }
🔥 1
c
wait whaaa. Never seen that before. damn. let me give it a whirl
Okay, so is there a chance that only works with proto datastore and not dataStorePreferences?
c
i think im just an idiot. these function types that are actually lambdas take a sec to register correctly. lol
😂 1
but okay. so updateData is not what I need. seems like I just need edit, but inside of edit I should be able to access the data too
hm. yeah. i think that example has a mistake on the parens too. just updated the ticket
t
BTW always use those update functions if you do not want race when updating based on previous version.
c
am i missing something though? I can't use an update function. All I can do is edit
t
Yes depending on what you use it's called differently but the concept is the same it's atomic with transformer
Copy code
dataStore.edit { prefs -> prefs[COUNTER_KEY] = prefs[COUNTER_KEY] :? 0 + 1 } `
You need to do the read and the calculation in the transformer.
c
aha. okay. so
dataStore.edit { prefs -> prefs[COUNTER_KEY] = (prefs[COUNTER_KEY] ?: 0) + 1 }
is what I have (elvis operator is wrong in the docs, and I believe it requires parens or else the ?: 0 + 1 will always set the value to 1 or the previous value.
thanks for the sanity checks everyone. indeed i should just do it in a single call.
t
Yes docs are wrong, you can verify with https://kotlinlang.org/docs/reference/grammar.html#expressions that + is higher than ?: (always found that strange)
âž• 1
c
created a bug for the docs issues lol https://issuetracker.google.com/issues/340500571