Skip to content

Instantly share code, notes, and snippets.

@qureshiayaz29
Created October 4, 2025 09:21
Show Gist options
  • Select an option

  • Save qureshiayaz29/a6db1ced6c04974311a4308ddf2bdaa9 to your computer and use it in GitHub Desktop.

Select an option

Save qureshiayaz29/a6db1ced6c04974311a4308ddf2bdaa9 to your computer and use it in GitHub Desktop.
class UserViewModel(private val getUsersUseCase: GetUsersUseCase) : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
init {
loadUsers()
}
fun loadUsers() {
viewModelScope.launch {
getUsersUseCase().collect { result ->
_uiState.value = when (result) {
is Result.Loading -> UiState.Loading
is Result.Success -> UiState.Success(result.data)
is Result.Error -> UiState.Error(result.message)
}
}
}
}
}
// UserListScreen.kt
@Composable
fun UserListScreen(viewModel: UserViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
when (val state = uiState) {
is UiState.Loading -> LoadingIndicator()
is UiState.Success -> {
LazyColumn {
items(state.users) { user ->
UserItem(user)
}
}
}
is UiState.Error -> ErrorMessage(state.message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment