Last active
December 21, 2021 12:03
-
-
Save cp-radhika-s/0092ff7529b9a43797d87e0bb7b607c0 to your computer and use it in GitHub Desktop.
Jetpack Compose + MVVM + Kotlin Coroutine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@HiltViewModel | |
class MainViewModel | |
@Inject constructor(private val userServices: UserServices) : ViewModel() { | |
val state = MutableStateFlow<State>(State.START) | |
init { | |
loadUser() | |
} | |
private fun loadUser() = viewModelScope.launch { | |
state.value = State.LOADING | |
try { | |
val users = withContext(Dispatchers.IO) { userServices.getUsers() } | |
state.value = State.SUCCESS(users) | |
} catch (e: Exception) { | |
state.value = State.FAILURE(e.localizedMessage) | |
} | |
} | |
} | |
sealed class State { | |
object START : State() | |
object LOADING : State() | |
data class SUCCESS(val users: List<User>) : State() | |
data class FAILURE(val message: String) : State() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment