https://kotlinlang.org logo
Title
k

kotlinforandroid

07/01/2022, 11:56 AM
Is there a way to leverage
remember
in combination with Proto DataStores? I've defined my
DataStore
:
val Context.dataStore: DataStore<AppPreferences> = dataStore(serializer = ..., ...)
However, I would like to have a way to fetch single values inside composables:
@Composable
fun SomeUI() {
    val context = LocalContext.current
    var userFontSize by remembe { context.dataStore.data.fontSize } // or something similar

    // Re-composition happens if the value changes for some reason. And it also gets stored if the var changes.
}
It's easy to do with a
SharedPreferences
-backed
DataStore
since I can use keys to fetch the value and set it. But I am not sure how to do it with Protobufs.
a

Adam Powell

07/01/2022, 1:04 PM
You should be able to observe the data store's flow with
collectAsState
or
produceState
k

kotlinforandroid

07/01/2022, 1:50 PM
collectAsState
only makes is so I can keep up-to-date with it being changed externally. And I do not see how
produceState
helps me here. Isn't that function meant for data that, without any influence, changes? Like timers. I just don't see how I can use it to update my data store when I assign a new value:
userFontSize = 12
.
s

Stylianos Gakis

07/01/2022, 1:58 PM
When you edit your DataStore the flows automatically emit the new value. So if you start collecting that flow with either way that Adam suggests you will receive the latest value when it changes.
☝️ 1