I'm having trouble seeing how the parts fit togeth...
# compose
r
I'm having trouble seeing how the parts fit together. Eg, I have a
NavHost(...) { composable(..., arguments = ...) {
... inside that I extract at argument (id: String), now I can want to query my Room database, like
db.getThing(id):Flow<Thing>
and pass it to a
@Composable fun ThingView(thing)
but that DB function is not callable outside of a coroutine context. So... where do I get the coroutine context, and then how to I hook the result obtained within that back to some MutableState that Compose can observe, in ThingView.
i
Room methods that return a
Flow<Thing>
should not be
suspend
methods, so you just call it directly and call
collectAsState()
on the Flow as per https://developer.android.com/jetpack/compose/libraries#streams
r
Okay, my code seems to work. One thing looks awkward - maybe it's normal but tutorials tend not to show it – the DB returns Flow<Thing?>, like most "get by ID" functions. So all these composables have a some boilerplate checking the state value for null (and Kotlin's smart casts won't work on the
val state by flow.collectAsState(initial=null)
so there's an extra assignment to a local. But maybe that's just reality. The UI does need to wait for a DB query. It's just that the docs tend to use simpler examples.
I'm trying to understand what thread actually sets that state value when the DB gets a result. I'm finding coroutines harder to understand than good old threads.
i
Yeah, that null check actually makes it incredibly easy to write whatever loading spinner, etc. you want as the null branch of your if statement - you output one set of composables when it is null vs another set when it is non-null
👍 1
d
Coroutines are like baby threads in adult threads.