Most apps talk to a server. Retrofit turns a REST API into a simple Kotlin interface and (with a converter) parses JSON into your data classes.
Define the API
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") id: Int): User
@GET("products")
suspend fun products(@Query("page") page: Int): List<Product>
}
Build Retrofit
val api = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
Call it safely
viewModelScope.launch {
try {
val user = api.getUser(42) // suspend, off main thread
_state.value = UiState.Success(user)
} catch (e: Exception) {
_state.value = UiState.Error(e.message)
}
}
Common mistake: Add the INTERNET permission in the manifest, and always wrap network calls in try/catch — networks fail often.
Summary
Retrofit + a JSON converter makes API calls declarative. Call suspend functions from a coroutine and handle errors gracefully.