Lesson 19: Making Network Requests: Introduction to Retrofit
Making Network Requests: Introduction to Retrofit
Time to fetch real data from an actual API instead of hardcoded lists. We'll use Retrofit, the standard networking library across the Android ecosystem.
Add the dependencies
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-gson:2.11.0")
implementation("androidx.compose.runtime:runtime-livedata:1.7.0")Declare your API endpoint
interface TaskApi {
@GET("todos")
suspend fun getTasks(): List
}The suspend keyword marks this as a coroutine — Kotlin's way of running long operations (like a network call) without freezing the UI while waiting. We'll use suspend functions constantly from here on; for now, just know it means "this can take time, and won't block the app while it does."
Build the Retrofit instance
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val taskApi = retrofit.create(TaskApi::class.java)We're using JSONPlaceholder, a free fake API perfect for learning — no API key, no backend of your own required.
Calling it from a ViewModel
class TaskListViewModel : ViewModel() {
var tasks by mutableStateOf>(emptyList())
private set
init {
viewModelScope.launch {
tasks = taskApi.getTasks()
}
}
}viewModelScope.launch { } is how you call a suspend function from a ViewModel — it runs the network call in the background and automatically cancels it if the ViewModel is destroyed, so you never leak a request nobody's waiting for anymore.
Next: Lesson 20 — properly modeling the JSON data this API actually returns.