-
Notifications
You must be signed in to change notification settings - Fork 7
/
UserViewModel.kt
55 lines (46 loc) · 1.8 KB
/
UserViewModel.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
50
51
52
53
54
55
package org.ericampire.android.demoapp.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import org.ericampire.android.demoapp.UserState
import org.ericampire.android.demoapp.UserIntent
import org.ericampire.android.demoapp.app.arch.IModel
import org.ericampire.android.demoapp.model.UserApi
class UserViewModel(private val userApi: UserApi) : ViewModel(), IModel<UserState, UserIntent> {
override val intents: Channel<UserIntent> = Channel(Channel.UNLIMITED)
private val _state = MutableLiveData<UserState>().apply { value = UserState() }
override val state: LiveData<UserState>
get() = _state
init {
handlerIntent()
}
private fun handlerIntent() {
viewModelScope.launch {
intents.consumeAsFlow().collect { userIntent ->
when(userIntent) {
UserIntent.RefreshUsers -> fetchData()
UserIntent.FetchUsers -> fetchData()
}
}
}
}
private fun fetchData() {
viewModelScope.launch(Dispatchers.IO) {
try {
updateState { it.copy(isLoading = true) }
updateState { it.copy(isLoading = false, users = userApi.getUser()) }
} catch (e: Exception) {
updateState { it.copy(isLoading = false, errorMessage = e.message) }
}
}
}
private suspend fun updateState(handler: suspend (intent: UserState) -> UserState) {
_state.postValue(handler(state.value!!))
}
}