Last active
August 18, 2019 13:41
-
-
Save marcinOz/6a2eeaf3fa8b0252b6b1e4ebf64d4fe4 to your computer and use it in GitHub Desktop.
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
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