Skip to content

Instantly share code, notes, and snippets.

@TheBotBox
Last active June 7, 2020 11:59
Embed
What would you like to do?
class MainViewModel(
private val iRepository: IRepository
) : ViewModel() {
private val _errorLiveData: MutableLiveData<String> = MutableLiveData()
val errorLiveData: LiveData<String>
get() = _errorLiveData
private val _fetchRandomQuoteLiveData: MutableLiveData<RandomQuoteResponse> = MutableLiveData()
val fetchRandomQuoteLiveData: LiveData<RandomQuoteResponse>
get() = _fetchRandomQuoteLiveData
fun fetchQuoteFromServer() = viewModelScope.launch {
try {
_fetchRandomQuoteLiveData.value = iRepository.fetchRandomQuote()
} catch (e: ApiException) {
_errorLiveData.value = e.message
} catch (e: NoInternetException) {
_errorLiveData.value = e.message
} catch (e: Exception) {
_errorLiveData.value = e.message
}
}
fun addQuoteToDB() = viewModelScope.launch {
val randomQuote = _fetchRandomQuoteLiveData.value
if (randomQuote != null) {
iRepository.addQuoteToDB(randomQuote)
_errorLiveData.value = "Saved to database"
} else {
_errorLiveData.value = "No Quote available to save."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment