Skip to content

Instantly share code, notes, and snippets.

@AlexGabor
Created August 30, 2022 14:38
Show Gist options
  • Save AlexGabor/6bbe51aece4cb7da8e86a1a4ee5d6429 to your computer and use it in GitHub Desktop.
Save AlexGabor/6bbe51aece4cb7da8e86a1a4ee5d6429 to your computer and use it in GitHub Desktop.
state holder instead of vm
@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