Skip to content

Instantly share code, notes, and snippets.

@Ahmedgadein
Created March 21, 2022 11:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ahmedgadein/a2730936941c7d91dc663cb97d0e2b14 to your computer and use it in GitHub Desktop.
Save Ahmedgadein/a2730936941c7d91dc663cb97d0e2b14 to your computer and use it in GitHub Desktop.
class LoginViewModel(val repository: AuthRepository): ViewMode() {
private val _state = mutableStateOf(LoginUiState())
val state = _state.asStateFlow()
fun onLoginAttemp(user: User) {
viewModelScope.launch {
repository.isRegistered(user).collect { registered ->
when (registered) {
is Result.Loading -> {
_state.update { it.copy(loading = true) }
}
is Result.Error -> {
showUserMessage(registered.message)
}
is Result.Success -> {
repository.signIn(user).collect { signedIn ->
when (signedIn) {
is Result.Loading -> {
_state.update { it.copy(loading = true) }
}
is Result.Error -> {
showUserMessage(signedIn.message)
}
is Result.Success -> {
_state.update {
loading = false,
// User is registered and signing in was successful
navigateToHome = registered.value && signedIn.value
// User is not registered and this is the first sign in
navigateToRegistration = !registered.value && signedIn.value
}
}
}
}
}
}
}
}
}
fun showUserMessage(message: String) {
_state.update {
val messages = it.errorMessages + message
it.copy(errorMessages = messages)
}
}
fun userMessageShown() {
_state.update{
// Remove last message
val messages = it.messages.subList(0, it.messages.size -1)
it.copy(errorMessages = messages)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment