Skip to content

Instantly share code, notes, and snippets.

@TheBotBox
Last active June 7, 2020 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheBotBox/1456c9a2dc7525ced31df0743b146495 to your computer and use it in GitHub Desktop.
Save TheBotBox/1456c9a2dc7525ced31df0743b146495 to your computer and use it in GitHub Desktop.
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