forked from next-step/android-github-compose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGithubRepositoryViewModel.kt
88 lines (77 loc) · 3.06 KB
/
GithubRepositoryViewModel.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package nextstep.github.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import nextstep.github.GithubApplication
import nextstep.github.data.GithubRepository
import nextstep.github.ui.model.GithubRepositoryModel
import nextstep.github.ui.model.toGithubRepositoryModel
class GithubRepositoryViewModel(
private val githubRepository: GithubRepository,
) : ViewModel() {
private val _state = GithubRepositoryStateImpl()
val state: GithubRepositoryState = _state
init {
loadRepositories()
}
fun loadRepositories() {
viewModelScope.launch {
githubRepository.getRepositories(
organization = NEXT_STEP_ORGANIZATION,
onPreLoad = {
_state.repositoryUiState.update { GithubRepositoryState.RepositoryUiState.Loading }
}
)
.onSuccess { data ->
val result = data.mapNotNull { it.toGithubRepositoryModel() }
_state.repositoryUiState.update {
if (result.isEmpty()) {
GithubRepositoryState.RepositoryUiState.Empty
} else {
GithubRepositoryState.RepositoryUiState.Data(result)
}
}
}
.onError { t ->
_state.repositoryUiState.update {
GithubRepositoryState.RepositoryUiState.Error(t)
}
}
}
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val githubRepository =
(this[APPLICATION_KEY] as GithubApplication).appContainer.githubRepository
GithubRepositoryViewModel(githubRepository)
}
}
}
}
interface GithubRepositoryState {
val repositoryUiState: StateFlow<RepositoryUiState>
sealed interface RepositoryUiState {
data object Idle : RepositoryUiState
data object Loading : RepositoryUiState
data object Empty : RepositoryUiState
data class Data(val items: List<GithubRepositoryModel>) : RepositoryUiState
data class Error(val t: Throwable? = null) : RepositoryUiState
}
}
class GithubRepositoryStateImpl(
override val repositoryUiState: MutableStateFlow<GithubRepositoryState.RepositoryUiState> = MutableStateFlow(
GithubRepositoryState.RepositoryUiState.Idle
)
) : GithubRepositoryState
sealed interface GithubRepositoryEvent {
data object ShowSnackBar : GithubRepositoryEvent
}
private const val NEXT_STEP_ORGANIZATION = "next-step"