Skip to content

Instantly share code, notes, and snippets.

@attilakruchio
Created July 3, 2022 14:14
Show Gist options
  • Save attilakruchio/b244828c22b82af6930515056492d54b to your computer and use it in GitHub Desktop.
Save attilakruchio/b244828c22b82af6930515056492d54b to your computer and use it in GitHub Desktop.
Gist for 'Taking care of process death with minimal pain using ViewModel' Medium article
@HiltViewModel
class MainViewModel @Inject constructor(
private val hotelRepository: HotelRepository
) : ViewModel() {
private val _filterBySustainability = MutableStateFlow(false)
private val _hotels = MutableStateFlow<List<Hotel>>(emptyList())
val state = combine(
_hotels, _filterBySustainability
) { hotels, filterBySustainability ->
State(
isFiltered = filterBySustainability,
hotels = when {
filterBySustainability -> hotels.filter(Hotel::sustainable)
else -> hotels
}
)
}.distinctUntilChanged()
fun loadHotels() {
viewModelScope.launch {
_hotels.value = hotelRepository.getHotels()
}
}
fun toggleFilterBySustainability() {
_filterBySustainability.update { filtered ->
!filtered
}
}
data class State(
val isFiltered: Boolean,
val hotels: List<Hotel>,
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment