Building an Android App with Jetpack Compose, Retrofit, and MVVM Architecture

Jaykishan Sewak
3 min readSep 19, 2023

--

Folks recently I started exploring jetpack compose, so after playing with designs I tried to male an API call using MVVM architecture, so today we will talk about that.

In this guide, we’ll walk through the process of creating an Android app that makes API calls using Jetpack Compose, Retrofit, and follows the MVVM (Model-View-ViewModel) architecture. By the end, you’ll have a good understanding of how to build a modern and efficient Android app.

Prerequisites

Before we begin, ensure you have the following prerequisites:

- Android Studio (with Kotlin support)
- Basic knowledge of Jetpack Compose, Retrofit, and MVVM architecture.

Step 1: Create a New Project

Let’s kick things off by creating a new Android project. Follow these steps:

1. Open Android Studio.

2. Click on “Start a new Android Studio project” or navigate to `File > New > New Project`.

3. In the project setup wizard, choose an “Empty Compose Activity” as your project template.

4. Click “Finish” to create your project.

Step 2: Add Dependencies

Now that our project is set up, we need to include some essential dependencies. These libraries will help us with API requests, ViewModel management, and LiveData:

dependencies {
// … your other dependencies …
// Retrofit for API requests
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
// ViewModel and LiveData for MVVM architecture
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07"
implementation "androidx.lifecycle:lifecycle-livedata:2.3.1"
}

After adding these dependencies, don’t forget to sync your project by clicking the “Sync Now” button.

Step 3: Create an API Interface

In this step, we’ll create an interface that defines the API endpoints using Retrofit. Here’s how:

1. Create a new Kotlin interface file. You can name it `ApiService.kt`.

2. Define your API interface using Retrofit annotations. For instance:

interface ApiService {
@GET("posts")
suspend fun getPosts(): List < Post >
}

In this example, we assume that `Post` is a data class representing the API response structure.

Step 4: Establish a Retrofit Instance

Now, let’s set up a singleton Retrofit instance. This instance will handle the actual API calls. Follow these steps:

1. Create a Kotlin file, typically named `RetrofitInstance.kt`.

2. Inside this file, implement the Retrofit singleton:

object RetrofitInstance {
private
const val BASE_URL = "https://jsonplaceholder.typicode.com/"
val api: ApiService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(ApiService::class.java)
}
}

Make sure to replace `BASE_URL` with the base URL of your API.

Step 5: Develop the ViewModel

Time to create a ViewModel class that will handle data management for our Composable. Here’s how:

1. Create a new Kotlin class file, say `MainViewModel.kt`.

2. Inside this file, define your ViewModel class:

class MainViewModel: ViewModel() {
private val apiService = RetrofitInstance.api
val posts: MutableState < List < Post >> = mutableStateOf(emptyList())
fun getPosts() {
viewModelScope.launch {
try {
val response = apiService.getPosts()
if (response.isNotEmpty()) {
posts.value = response
}
} catch (e: Exception) {
// Handle errors here
}
}
}
}

Step 6: Create a Composable

Now, let’s create a Composable function that displays the API data:

1. Develop a Composable file, such as `PostList.kt`.

2. Inside this file, create the Composable:

@Composable
fun PostList(viewModel: MainViewModel) {
val posts by viewModel.posts.collectAsState()
LazyColumn {
items(posts) {
post ->
Text(text = post.title)
}
}
DisposableEffect(Unit) {
viewModel.getPosts()
onDispose {}
}
}

Step 7: Set Up the UI

Lastly, let’s update the `MainActivity` to use our Composable:

1. Open the `MainActivity.kt` file.

2. Modify the `MainActivity` class like this:

class MainActivity: AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle ? ) {
super.onCreate(savedInstanceState)
setContent {
MyApp {
PostList(viewModel = viewModel)
}
}
}
}

Step 8: Run the App

Now, it’s time to see your Android app in action. Click the “Run” button in Android Studio to deploy your app. It should fetch and display data from the API using Retrofit and MVVM architecture in Jetpack Compose.

Remember that this is just the beginning. Depending on your project’s complexity, you may need to implement features like loading states, error handling, pagination, and more to create a fully functional production-ready application.

I have also started contributing on GitHub for jetpack compose demos you can have look and start contributing

If you found article useful then please start following me. You can also find me on LinkedIn and GitHub.

You can find my more article on GFG portal also.

Happy coding! 🚀

--

--

Jaykishan Sewak

Mobile Lead | Android Tech Lead at HSBC | Flutter | MVVM | JetPack Compose | kotlin | Medium blog writer | GitHub Contributor