Jetpack Compose API Data to List View
Many times we need to make API calls to fetch data and display that data using a List. Here, I show how to do that with Compose. To illustrate the structure of the application let’s look at the following diagram
Firstly, Add Internet Permission to your Application in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Before we start let’s update our build.gradle file with the Retrofit HTTP client and aConverter
which uses Gson for serialisation to and from JSON.:
dependencies{...
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.0.0"
}
The Todo APIService
We need to create the Retrofit instance to send the network requests. we need to use the Retrofit Builder class and specify the base URL for the service. Here we have one GET to fetch all Todos and deserialise to List<Todo>
The Todo ViewModel
The View model publishes the todoList and has a getTodoList function for the view to use to fetch all todos
The Todo View
Finally we have the view which watches the ViewModel for any todo list state changes. The todo list is display in the view. On Launch the view makes the api call.