Use Retrofit with ViewModel and Coroutines for API calls in Jetpack Compose. Jetpack Compose doesn't handle HTTP directly.
groovy
CopyEdit
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1'
kotlin
CopyEdit
dataclass User(val id: Int, val email: String) interface ApiService { @GET("api/users") suspend fun getUsers(@Query("page") page: Int): UserResponse } object ApiClient { val api = Retrofit.Builder() .baseUrl("https://reqres.in/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiService::class.java) }
kotlin
CopyEdit
classUserViewModel : ViewModel() { var users by mutableStateOf<List<User>>(emptyList()) init { viewModelScope.launch { users = ApiClient.api.getUsers(1).data } } }
kotlin
CopyEdit
@Composable fun UserScreen(viewModel: UserViewModel = viewModel()) { LazyColumn { items(viewModel.users) { user -> Text("${user.id}: ${user.email}") } } }