Fetching Data from Api in Jetpack compose

Emmanuel Iyke
2 min readAug 16, 2022

Fetching api in jetpack compose can be tricky, especially when it comes to thread handling.

Today we are going to use MVVM architecture to fetch data from an api and display it in a listview with expandable list item.

Note: It is important to mention that jetpack compose is only available in kotlin and not java, it uses features like coroutine and kotlin compiler to handle @Composable annotations. So click here to get started with kotlin for android development.

Add the following dependencies to your Android project

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"implementation "com.google.accompanist:accompanist-swiperefresh:0.26.1-alpha"

Next add an Internet permission to your manifest.

<uses-permission android:name=”android.permission.INTERNET”/>

We will be fetching our jokes from https://sv443.net/jokeapi/v2/

So the Api result would be structured like this

From the structure of the json file we need to create two model classes. One holding a list of the jokes and the other holding the joke items, Along with an Interface that calls the list Api.

Next we create a viewmodel that has a mutable list array of the joke class and a string that passes a mutable string for any error message that would occour

Finally we now have to update the joke items into the listview

Link to the project on github

Whoo! That is all for now.

If you want me to make an article on something you want to understand, Or you have any questions, do let me know in comments.

If the articles are helpful to you, let’s connect on twitter or on github.

Follow for more helpful contents like this on Android and jetpack compose

Until next time…

Cheers!

--

--