Retrofit with Kotlin Coroutines
- Authors
- Name
- Amit Shekhar
- Published on
To use Retrofit with Kotlin Coroutines, we mark the API interface functions with the suspend keyword, and then call them from a coroutine inside the ViewModel.
In this blog, we will learn how to use Retrofit with Kotlin Coroutines in Android. We will learn to write the code inside the ViewModel with Kotlin Coroutines that follows a basic MVVM Architecture.
I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
I teach AI and Machine Learning, and Android at Outcome School.
Join Outcome School and get a high-paying tech job:
Let's get started.
I will be using the following project for the implementation part. The project follows a basic MVVM Architecture for simplicity. You can find the complete code for the implementation mentioned in this blog in the project itself.
GitHub Project: Learn Kotlin Coroutines
First, we need to set up our dependencies for the Retrofit as below:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Note: Always check for the latest available version.
As I am using the Gson to parse JSON into Java and Kotlin classes, I have added the dependency for the Gson. You can add based on your requirement.
Now, create the data class ApiUser as below:
data class ApiUser(
@SerializedName("id")
val id: Int = 0,
@SerializedName("name")
val name: String = "",
@SerializedName("email")
val email: String = "",
@SerializedName("avatar")
val avatar: String = ""
)
Now, we need to create the ApiService interface required for Retrofit.
interface ApiService {
@GET("users")
suspend fun getUsers(): List<ApiUser>
@GET("more-users")
suspend fun getMoreUsers(): List<ApiUser>
@GET("error")
suspend fun getUsersWithError(): List<ApiUser>
}
Note: We have used suspend keyword to support Coroutines so that we can call it from a Coroutine or another suspend function.
After this, we will be needing a class RetrofitBuilder which will be a Singleton.
object RetrofitBuilder {
private const val BASE_URL = "https://5e510330f2c0d300147c034c.mockapi.io/"
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}
Then, we will create an interface ApiHelper.
interface ApiHelper {
suspend fun getUsers(): List<ApiUser>
suspend fun getMoreUsers(): List<ApiUser>
suspend fun getUsersWithError(): List<ApiUser>
}
Note: Again, we have used suspend keyword to support Coroutines so that we can call it from a Coroutine or another suspend function.
A quick note for you
No matter which tech domain you work in, get familiar with these topics:
- LLM
- RAG
- MCP
- Agent
- Fine-tuning
- Quantization
We put it all together in one video:
AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization
No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.
Now, let's get back to the topic.
After that, we will create a class ApiHelperImpl that implements the ApiHelper interface.
class ApiHelperImpl(private val apiService: ApiService) : ApiHelper {
override suspend fun getUsers() = apiService.getUsers()
override suspend fun getMoreUsers() = apiService.getMoreUsers()
override suspend fun getUsersWithError() = apiService.getUsersWithError()
}
Once we've done that, we can create the instance of ApiHelper as below:
val apiHelper = ApiHelperImpl(RetrofitBuilder.apiService)
Finally, we can pass this instance wherever required, for example to the ViewModel, and make the network call to get the users from the network as below:
class SingleNetworkCallViewModel(private val apiHelper: ApiHelper, private val dbHelper: DatabaseHelper) : ViewModel() {
init {
fetchUsers()
}
private fun fetchUsers() {
viewModelScope.launch {
try {
val usersFromApi = apiHelper.getUsers()
// list of users from the network
} catch (e: Exception) {
// handle exception
}
}
}
}
This way, we are able to fetch the data from the network using Retrofit with Kotlin Coroutines in Android.
I must mention that you can learn much more from the GitHub repository that I mentioned above in this blog. You can learn the following:
- Making network calls in series using Retrofit with Kotlin Coroutines.
- Making multiple network calls in parallel using Retrofit with Kotlin Coroutines.
This is how we can use Retrofit with Kotlin Coroutines in Android.
To master Retrofit, OkHttp Interceptor, Coroutines internals, and MVVM Clean Architecture by building real projects like NewsApp, check out the Android Program by Outcome School.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
Frequently Asked Questions
Why do we mark the Retrofit ApiService functions with suspend?
We use the suspend keyword to support Coroutines. A suspend function can be called from a Coroutine or from another suspend function. So, the ViewModel can call the API inside viewModelScope.launch and get the list of users directly as the result.
How do we handle errors when calling Retrofit with Coroutines?
We wrap the network call in a try-catch block inside the coroutine. If the call succeeds, we get the list of users from the network. If it fails, the exception is caught in the catch block, where we handle it.
Do we have to use Gson with Retrofit?
No. Gson is used here to parse JSON into Java and Kotlin classes, so its converter dependency is added. We can add a different converter based on our requirement.
Can we make multiple network calls with Retrofit and Kotlin Coroutines?
Yes. Using Retrofit with Kotlin Coroutines, we can make network calls in series, and we can also make multiple network calls in parallel. The Learn Kotlin Coroutines project on GitHub shows both of these cases.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
