Created
June 27, 2024 15:44
-
-
Save anitaa1990/ecadc0db52f55d3e1801b8deac36958c to your computer and use it in GitHub Desktop.
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 ContactsViewModel @Inject constructor( | |
private val contactsRepository: ContactsRepository | |
) : ViewModel() { | |
// We are defining a MutableStateFlow for the `ContactUiState` with an | |
// initial value of loading = true. So when the app is first launched, | |
// a loading screen will be displayed while we fetch the contacts list. | |
private val _uiState = MutableStateFlow(ContactUiState(loading = true)) | |
val uiState = _uiState.asStateFlow() | |
init { | |
// When the ViewModel is first initialized, we update the `ContactUiState` | |
// loading state as true while we fetch the contact list from the device. | |
viewModelScope.launch { | |
_uiState.update { it.copy(loading = true) } | |
getContacts() | |
} | |
} | |
// Once the contact list is fetched, we sort the list | |
// alphabetically and then update the Ui with the contact list | |
// and set the loading state as false. | |
private fun getContacts() = viewModelScope.launch { | |
val contacts = contactsRepository.getContacts().groupBy { contact -> | |
contact.displayName.first().toString() | |
} | |
_uiState.update { it.copy( | |
loading = false, | |
contacts = contacts | |
) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment