I have a question around SQLDelight and the Flow e...
# squarelibraries
a
I have a question around SQLDelight and the Flow extension: • I have a view that displays a list of objects. For that I query a Flow<List<T>> and call collectAsState() in my composable and it works fine. • What about if there's a single object that I need to fetch immediately to be able to render my UI, but I also want to get updated if the database changes? Is there still a way to use Flows in that case? I'm still new to kotlin flows so please bear with me :)
d
If I'm understanding the question correctly, is this about passing an initial value to
collectAsState()
?
a
No, is just about getting a single object synchronously but still use a Flow, so I can get updates later on. I guess I can use the
first()
method actually to get the first value
d
Ah, in that case you can just use the
mapToOne()
or
mapToOneOrNull()
functions Those will give you
Flow<T>
and
Flow<T?>
respectively
a
I guess the thing is I want to have a member variable of type
T
so that any part of my UI can just access that variable or use it to query child items etc. But a
Flow
is more like a channel where you wait for data to come in
Ooh I think what I want is what
collectAsState
does, just have to call it in my *State class
Actually no,
collectAsState
can only be called from a Composable. So it seems I want to use
stateIn
to convert the flow to a StateFlow
g
If you don't know it yet, you may want to have a look at Molecule.
s
The quickest way to do this without branching out to things like Molecule sounds like it’d be to do exactly what you say, observe and cache the last value by turning that flow into a
StateFlow
in wherever you are holding your state, and then on the UI layer you can both observe it and even get it instantly by using the
value
field that
StateFlow
exposes.
a
@glureau @Stylianos Gakis Thanks guys. What would be the difference if I use molecule vs. creating a StateFlow in my ViewState class?
g
Molecule offers a new paradigm, so that you can define your store/ViewModel as a composable function (it doesn't force you to use ComposeUI btw). The fact that it's defined as a function means more usage of Compose State to maintain stuff in RAM, compared to a class instance that is more typical usage. If you start a new project / side project it may be worth it to learn, if you don't have spare time and want a quick win then @Stylianos Gakis approach is more pragmatic, quicker to setup and close to your current knowledge I presume.
a
I found a writeup about molecule from Reddit eng that explains the benefits of the library: https://www.reddit.com/r/RedditEng/comments/wjc00j/reactive_ui_state_on_android_starring_compose/
417 Views