Skip to content

Instantly share code, notes, and snippets.

@marcinOz
Last active August 18, 2019 13:41
Show Gist options
  • Save marcinOz/6a2eeaf3fa8b0252b6b1e4ebf64d4fe4 to your computer and use it in GitHub Desktop.
Save marcinOz/6a2eeaf3fa8b0252b6b1e4ebf64d4fe4 to your computer and use it in GitHub Desktop.
class MyViewModel(
private val getDataUseCase: GetDataUseCase,
private val contextProvider: CoroutineContextProvider
) : ViewModel() {
private val handler = CoroutineExceptionHandler { _, exception ->
stateLiveData.value = MyViewState.Error(exception)
}
private val stateLiveData = MutableLiveData<MyViewState>()
fun getStateLiveData(): LiveData<MyViewState> = stateLiveData
fun getData() {
stateLiveData.value = MyViewState.Loading
viewModelScope.launch(handler) {
val data = withContext(contextProvider.IO) {
getDataUseCase.fetchFromServer()
}
stateLiveData.value = MyViewState.Success(data)
}
}
}
sealed class MyViewState {
object Loading : MyViewState()
data class Error(val throwable: Throwable) : MyViewState()
data class Success(val data: Any) : MyViewState()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment