Skip to content

Instantly share code, notes, and snippets.

@DenisBronx
Last active October 15, 2019 13:28
Show Gist options
  • Save DenisBronx/c7cf144016aec5245d4c5b528e5f2259 to your computer and use it in GitHub Desktop.
Save DenisBronx/c7cf144016aec5245d4c5b528e5f2259 to your computer and use it in GitHub Desktop.
ViewModel without usecases
class TransactionsViewModelImpl(
private val userRepository: UserRepository,
private val transactionRepository: TransactionRepository
) : 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() {
when (val result = userRepository.getUser()) {
is Result.Success -> loadUserTransactions(result.value)
is Result.Failure -> setErrorState()
}
}
private fun loadUserTransactions(user: User) {
setLoadState()
transactionRepository.getUserTransactions(user)
.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