Junior — Middle
How to implement an asynchronous HTTP request using Retrofit and coroutines in an Android project?
sobes.tech AI
Answer from AI
To implement an asynchronous HTTP request with Retrofit and coroutines in Android, you need to:
- Add dependencies for Retrofit and Kotlin Coroutines to your project.
- Define an API interface with a function that returns a
Deferredor asuspendfunction. - Call this function from a coroutine using
suspend.
Example of an API interface with a suspend function:
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: String): User
}
Example of calling from a ViewModel or another coroutine:
viewModelScope.launch {
try {
val user = apiService.getUser("123")
// handle the retrieved user
} catch (e: Exception) {
// handle the error
}
}
Thus, Retrofit integrates with coroutines through suspend functions, simplifying asynchronous code and making it more readable.