1
1
package app.softwork.composetodo.viewmodels
2
2
3
+ import androidx.compose.runtime.*
4
+ import app.cash.molecule.*
3
5
import app.softwork.composetodo.*
4
6
import kotlinx.coroutines.*
5
7
import kotlinx.coroutines.flow.*
@@ -8,27 +10,49 @@ class LoginViewModel(
8
10
private val api : API .LoggedOut ,
9
11
private val onLogin : (API .LoggedIn ) -> Unit
10
12
) : ViewModel() {
11
- val userName = MutableStateFlow (" " )
12
- val password = MutableStateFlow (" " )
13
+ data class LoginState (
14
+ val userName : String ,
15
+ val password : String ,
16
+ val enableLogin : Boolean ,
17
+ val error : Failure ?
18
+ )
13
19
14
- val error = MutableStateFlow <Failure ?>(null )
20
+ private var userName by mutableStateOf(" " )
21
+ fun updateUserName (new : String ) {
22
+ userName = new
23
+ }
24
+ private var password by mutableStateOf(" " )
25
+ fun updatePassword (new : String ) {
26
+ password = new
27
+ }
28
+ private var error by mutableStateOf<Failure ?>(null )
29
+ fun dismissError () {
30
+ error = null
31
+ }
32
+
33
+ fun state (clock : RecompositionClock = RecompositionClock .ContextClock ): StateFlow <LoginState > = lifecycleScope.launchMolecule(clock) {
34
+ val isError = userName.isNotEmpty() && password.isNotEmpty()
15
35
16
- val enableLogin = userName.combine(password) { userName, password ->
17
- userName.isNotEmpty() && password.isNotEmpty()
36
+ LoginState (
37
+ userName = userName,
38
+ password = password,
39
+ enableLogin = isError,
40
+ error = error
41
+ )
18
42
}
19
43
20
44
fun login () {
21
- error.value = null
45
+ error = null
22
46
lifecycleScope.launch {
23
47
api.networkCall(
24
48
action = {
25
- login(username = userName.value , password = password.value )
49
+ login(username = userName, password = password)
26
50
}, onSuccess = {
27
- error.value = null
51
+ error = null
28
52
onLogin(it)
29
53
}
30
54
) {
31
- error.value = it
55
+ error = it
32
56
}
33
57
}
34
58
}
0 commit comments