File tree Expand file tree Collapse file tree
app/src/main/java/com/example/techexactly Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -3,10 +3,14 @@ package com.example.techexactly.di
33import com.example.techexactly.model.network.provideRetrofit
44import com.example.techexactly.model.network.provideUserApi
55import com.example.techexactly.model.repository.UserRepository
6+ import com.example.techexactly.viewmodel.MainViewModel
7+ import org.koin.core.module.dsl.viewModelOf
68import org.koin.dsl.module
79
810val appModule = module {
911 single { provideRetrofit() }
1012 single { provideUserApi(get()) }
1113 single { UserRepository (get()) }
14+
15+ viewModelOf(::MainViewModel )
1216}
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments