79677344

Date: 2025-06-24 09:37:08
Score: 1
Natty:
Report link

✅ Make API Request in Kotlin (Jetpack Compose)

Use Retrofit with ViewModel and Coroutines for API calls in Jetpack Compose. Jetpack Compose doesn't handle HTTP directly.


🔧 1. Add Dependencies

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'


📦 2. Setup Retrofit

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) }


👨‍💻 3. ViewModel

kotlin

CopyEdit

classUserViewModel : ViewModel() { var users by mutableStateOf<List<User>>(emptyList()) init { viewModelScope.launch { users = ApiClient.api.getUsers(1).data } } }


🎨 4. Compose UI

kotlin

CopyEdit

@Composable fun UserScreen(viewModel: UserViewModel = viewModel()) { LazyColumn { items(viewModel.users) { user -> Text("${user.id}: ${user.email}") } } }

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • User mentioned (1): @Composable
  • Low reputation (1):
Posted by: Saurabh Chauhan