5. Connect your queries to your UI
In this chapter, you are going to display a list of Launches in a LazyColumn.
Setup the LaunchList composable
In LaunchList
, declare a list of LaunchListQuery.Launch
, initialized as empty:
Kotlin
app/src/main/java/com/example/rocketreserver/LaunchList.kt
1@Composable
2fun LaunchList(onLaunchClick: (launchId: String) -> Unit) {
3 var launchList by remember { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }
LaunchListQuery.Launch
is a typesafe generated model from your LaunchList.graphql query.
Make a UI for the items
Update the LaunchItem
composable to pass it a LaunchListQuery.Launch
and display the id:
Kotlin
app/src/main/java/com/example/rocketreserver/LaunchList.kt
1@Composable
2private fun LaunchItem(launch: LaunchListQuery.Launch, onClick: (launchId: String) -> Unit) {
3 ListItem(
4 modifier = Modifier.clickable { onClick(launch.id) },
5 headlineText = {
6 // Mission name
7 Text(text = "Launch ${launch.id}")
8 },
Use the data in the list
Fill launchList
with the data from the response, and use it in the LazyColumn:
Kotlin
app/src/main/java/com/example/rocketreserver/LaunchList.kt
1@Composable
2fun LaunchList(onLaunchClick: (launchId: String) -> Unit) {
3 var launchList by remember { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }
4 LaunchedEffect(Unit) {
5 val response = apolloClient.query(LaunchListQuery()).execute()
6 launchList = response.data?.launches?.launches?.filterNotNull() ?: emptyList()
7 }
8
9 LazyColumn {
10 items(launchList) { launch ->
11 LaunchItem(launch = launch, onClick = onLaunchClick)
12 }
13 }
14}
Note: the
.filterNotNull()
is necessary because the schema defineslaunches
as a list of nullableLaunch
objects.
Test your query
Hit the Run button. You now have a UI connected to your GraphQL queries 🚀
It looks a bit plain, though. Next, you'll add more info to the list to make it look nicer!