Skip to content

Instantly share code, notes, and snippets.

@cp-radhika-s
Last active December 21, 2021 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cp-radhika-s/0092ff7529b9a43797d87e0bb7b607c0 to your computer and use it in GitHub Desktop.
Save cp-radhika-s/0092ff7529b9a43797d87e0bb7b607c0 to your computer and use it in GitHub Desktop.
Jetpack Compose + MVVM + Kotlin Coroutine
@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