Created
July 3, 2022 14:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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