Skip to content

Instantly share code, notes, and snippets.

@chiragthummar
Created December 25, 2023 06:20
Show Gist options
  • Save chiragthummar/9182c0eddd8e15c59ef367544f9832b1 to your computer and use it in GitHub Desktop.
Save chiragthummar/9182c0eddd8e15c59ef367544f9832b1 to your computer and use it in GitHub Desktop.
@HiltViewModel
class HomeScreenViewModel @Inject constructor(
private val imageRepository: ImageRepository
) : ViewModel() {
var state by mutableStateOf(HomeScreenState())
private set
fun onEvent(event: HomeScreenEvents) {
when (event) {
is HomeScreenEvents.LoadImages -> {
loadImages(event.q)
}
is HomeScreenEvents.UpdateText -> {
updateTextField(event.q)
}
}
}
private fun updateTextField(str: String) {
state = state.copy(text = str)
}
private fun loadImages(q: String) {
viewModelScope.launch {
imageRepository.getImages(q).collect { result ->
when (result) {
is Resources.Loading -> {
state = state.copy(isLoading = result.isLoading)
}
is Resources.Success -> {
println("Data in View model ${result.data}")
result.data?.let { listings ->
state = state.copy(
images = listings
)
}
}
is Resources.Error -> {
state = state.copy(isLoading = false)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment