Created
August 30, 2022 14:38
-
-
Save AlexGabor/6bbe51aece4cb7da8e86a1a4ee5d6429 to your computer and use it in GitHub Desktop.
state holder instead of vm
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
@Composable | |
fun LoginScreen( | |
modifier: Modifier = Modifier, | |
state: LoginScreenState = rememberLoginScreenState(), | |
) { | |
// ... | |
} | |
@Composable | |
fun rememberLoginScreenState( | |
stateScope: CoroutineScope = rememberCoroutineScope(), | |
doLogin: DoLogin = get(), // This is koin's get function. | |
onSignUp: () -> Unit = {}, | |
): LoginScreenState { | |
return rememberSaveable(saver = LoginScreenState.getSaver(stateScope, doLogin, onSignUp)) { | |
LoginScreenState(stateScope, doLogin, onSignUp) | |
} | |
} | |
class LoginScreenState( | |
private val stateScope: CoroutineScope, | |
private val doLogin: DoLogin, // Use Case for login | |
val onSignUpClick: () -> Unit, // sending the event up to be handled by the parent responsible for navigation | |
) { | |
var email: String by mutableStateOf("") | |
private set | |
var password: String by mutableStateOf("") | |
private set | |
var loading: Boolean by mutableStateOf(false) | |
private set | |
val loginEnabled by derivedStateOf { email.isNotEmpty() && password.isNotEmpty() } | |
var loginResult by mutableStateOf<LoginResult?>(null) | |
private set | |
val emailError: Boolean by derivedStateOf { loginResult is LoginResult.EmailPattern } | |
val passwordError: Boolean by derivedStateOf { loginResult is LoginResult.PasswordLength } | |
fun onEmail(text: String) { | |
email = text.trim() | |
} | |
fun onPassword(text: String) { | |
password = text | |
} | |
fun onLogin() { | |
stateScope.launch { | |
loading = true | |
loginResult = doLogin(email, password) | |
loading = false | |
} | |
} | |
fun dismissError() { | |
loginResult = null | |
} | |
companion object { | |
private const val EMAIL: String = "EMAIL" | |
private const val PASS: String = "PASS" | |
fun getSaver( | |
stateScope: CoroutineScope, | |
login: DoLogin, | |
onSignUp: () -> Unit, | |
): Saver<LoginScreenState, *> = mapSaver( | |
save = { mapOf(EMAIL to it.email, PASS to it.password) }, | |
restore = { | |
LoginScreenState(stateScope, login, onSignUp).apply { | |
onEmail(it.getOrElse(EMAIL) { "" } as String) | |
onPassword(it.getOrElse(PASS) { "" } as String) | |
} | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment