Skip to content

Commit b668070

Browse files
authored
Merge pull request #4 from CGreenP/dev
feat: Implement MainViewModel and UiState for user data display
2 parents 2d038cb + 5edecc5 commit b668070

3 files changed

Lines changed: 49 additions & 0 deletions

File tree

app/src/main/java/com/example/techexactly/di/AppModule.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@ package com.example.techexactly.di
33
import com.example.techexactly.model.network.provideRetrofit
44
import com.example.techexactly.model.network.provideUserApi
55
import com.example.techexactly.model.repository.UserRepository
6+
import com.example.techexactly.viewmodel.MainViewModel
7+
import org.koin.core.module.dsl.viewModelOf
68
import org.koin.dsl.module
79

810
val appModule = module {
911
single { provideRetrofit() }
1012
single { provideUserApi(get()) }
1113
single { UserRepository(get()) }
14+
15+
viewModelOf(::MainViewModel)
1216
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.example.techexactly.viewmodel
2+
3+
import androidx.lifecycle.ViewModel
4+
import androidx.lifecycle.viewModelScope
5+
import com.example.techexactly.model.repository.UserRepository
6+
import kotlinx.coroutines.flow.MutableStateFlow
7+
import kotlinx.coroutines.flow.StateFlow
8+
import kotlinx.coroutines.flow.asStateFlow
9+
import kotlinx.coroutines.launch
10+
11+
class MainViewModel(private val userRepository: UserRepository) : ViewModel() {
12+
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
13+
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
14+
15+
init {
16+
fetchUsers()
17+
}
18+
19+
fun fetchUsers() {
20+
viewModelScope.launch {
21+
userRepository.getUsers().collect { result ->
22+
when (result.isSuccess) {
23+
true -> {
24+
val users = result.getOrNull() ?: emptyList()
25+
_uiState.value = UiState.Success(users)
26+
}
27+
28+
false -> {
29+
val exception = result.exceptionOrNull()
30+
_uiState.value = UiState.Error(exception?.message ?: "Unknown Error")
31+
}
32+
}
33+
}
34+
}
35+
}
36+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.example.techexactly.viewmodel
2+
3+
import com.example.techexactly.model.dataclass.User
4+
5+
sealed class UiState {
6+
data object Loading : UiState()
7+
data class Success(val users: List<User>) : UiState()
8+
data class Error(val errorMessage: String) : UiState()
9+
}

0 commit comments

Comments
 (0)