4. Execute your first query
To execute your first query, you need to create an instance of ApolloClient
and make a new call with your query.
Create an ApolloClient
Create a new file named Apollo.kt in the com.example.rocketreserver
package and create an instance of ApolloClient
in it:
val apolloClient = ApolloClient.builder()
.serverUrl("https://apollo-fullstack-tutorial.herokuapp.com")
.build()
Note: apolloClient
is a top-level variable so that it can be reused from other parts of the app later on for better performance. Reusing the apolloClient
allows to reuse the underlying OkHttp instance and the associated threadpools and connections.
Creating the ApolloClient is as simple as giving it the endpoint of your GraphQL backend. It is https://apollo-fullstack-tutorial.herokuapp.com
in our case.
Execute the query
Open LaunchListFragment.kt
, override onViewCreated
and launch a new coroutine. Use the apolloClient and the generated LaunchListQuery
to execute a new query:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleScope.launchWhenResumed {
val response = apolloClient.query(LaunchListQuery()).await()
Log.d("LaunchList", "Success ${response?.data}")
}
}
Thanks to Kotlin coroutines, the query will be executed in a background thread even if the code looks synchronous.
Test your query
Hit run. You should see this in the logcat output:
2020-05-25 19:36:12.211 1835-1956/com.example.rocketreserver D/LaunchList: Success Data(launches=Launches(__typename=LaunchConnection, cursor=1547220660, hasMore=true, launches=[Launch(__typename=Launch, id=93, site=KSC LC 39A), Launch(__typename=Launch, id=92, site=KSC LC 39A), Launch(__typename=Launch, id=91, site=CCAFS SLC 40), Launch(__typename=Launch, id=90, site=CCAFS SLC 40), Launch(__typename=Launch, id=89, site=CCAFS SLC 40), Launch(__typename=Launch, id=88, site=KSC LC 39A), Launch(__typename=Launch, id=87, site=CCAFS SLC 40), Launch(__typename=Launch, id=86, site=CCAFS SLC 40), Launch(__typename=Launch, id=85, site=CCAFS SLC 40), Launch(__typename=Launch, id=84, site=CCAFS SLC 40), Launch(__typename=Launch, id=83, site=CCAFS SLC 40), Launch(__typename=Launch, id=82, site=CCAFS SLC 40), Launch(__typename=Launch, id=81, site=KSC LC 39A), Launch(__typename=Launch, id=80, site=VAFB SLC 4E), Launch(__typename=Launch, id=79, site=CCAFS SLC 40), Launch(__typename=Launch, id=78, site=CCAFS SLC 40), Launch(__typename=Launch, id=77, site=KSC LC 39A), Launch(__typename=Launch, id=76, site=KSC LC 39A), Launch(__typename=Launch, id=75, site=CCAFS SLC 40), Launch(__typename=Launch, id=74, site=VAFB SLC 4E)]))
This means the request was correctly executed and you now have a list of launch sites 🚀🚀🚀.
Next, let's connect this data to your UI.