Skip to content

Instantly share code, notes, and snippets.

@DenisBronx
Created October 15, 2019 13:50
Show Gist options
  • Save DenisBronx/7dda8498cb418aef703e494c9500ec9d to your computer and use it in GitHub Desktop.
Save DenisBronx/7dda8498cb418aef703e494c9500ec9d to your computer and use it in GitHub Desktop.
ViewModel with usecases
class TransactionsViewModelImpl(
private val getUserTransactionsUseCase: GetUserTransactionsUseCase
) : TransactionsViewModel, ViewModel() {
private val compositeDisposable = CompositeDisposable()
override val transactions = MutableLiveData<List<Transaction>>()
override val showProgress = MutableLiveData<Boolean>()
override val showError = MutableLiveData<Boolean>()
override val showContent = MutableLiveData<Boolean>()
override fun loadTransactions() {
setLoadState()
getUserTransactionsUseCase()
.subscribeBy {
handleResult(it)
}.addTo(compositeDisposable)
}
private fun setLoadState() {
showProgress.postValue(true)
showError.postValue(false)
showContent.postValue(false)
}
private fun handleResult(result: Result<List<Transaction>>) {
when (result) {
is Result.Success -> setContentState(result.value)
is Result.Failure -> setErrorState()
}
}
private fun setContentState(transactionsResult: List<Transaction>) {
showContent.postValue(true)
transactions.postValue(transactionsResult)
showProgress.postValue(false)
showError.postValue(false)
}
private fun setErrorState() {
showError.postValue(true)
showProgress.postValue(false)
showContent.postValue(false)
}
override fun onCleared() {
compositeDisposable.clear()
super.onCleared()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment