Created
March 21, 2022 11:33
-
-
Save Ahmedgadein/a2730936941c7d91dc663cb97d0e2b14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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