-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
AppContainer.kt
49 lines (43 loc) · 1.3 KB
/
AppContainer.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package app.softwork.composetodo
import app.softwork.composetodo.repository.*
import app.softwork.composetodo.viewmodels.*
import io.ktor.client.*
import io.ktor.utils.io.errors.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
class AppContainer(
val client: HttpClient,
val db: ComposeTodoDB
) : ViewModel() {
fun todoViewModel(): TodoViewModel {
val api = api.value as API.LoggedIn
return TodoViewModel(TodoRepository(api, db.todoQueries))
}
fun loginViewModel(): LoginViewModel {
val api = api.value as API.LoggedOut
return LoginViewModel(api) {
this.api.value = it
}
}
fun registerViewModel(): RegisterViewModel {
val api = api.value as API.LoggedOut
return RegisterViewModel(api) {
this.api.value = it
}
}
fun logout() {
lifecycleScope.launch {
when (val login = api.value) {
is API.LoggedIn -> {
try {
login.logout()
} catch (_: IOException) {
}
api.value = API.LoggedOut(client)
}
is API.LoggedOut -> {}
}
}
}
val api: MutableStateFlow<API> = MutableStateFlow(API.LoggedOut(client))
}