This file contains 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 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