Last active
October 15, 2019 13:28
-
-
Save DenisBronx/c7cf144016aec5245d4c5b528e5f2259 to your computer and use it in GitHub Desktop.
ViewModel without usecases
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 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