I am fetching currency exchange rate by api call using retrofit and ViewModel concept.On launch of application I am able to get the latest data from the server but when I am trying to update the live data by clicking the button, Live Data value is not updating, I am getting the same old data.So can anyone please help me out how to update live Data on button click event.
ViewModel Class*****
class MainViewModel(private val repository: CurrencyRepository) : ViewModel() {
init {
viewModelScope.launch() {
repository.getCurrencyExchangeList()
}
}
val quotes: LiveData<CurrencyData>
get() = repository.currencyLiveData
}
Repository Class*****
class CurrencyRepository(private val currencyService: CurrencyInterface) {
val currencyLiveData = MutableLiveData<CurrencyData>()
suspend fun getCurrencyExchangeList() {
val result = currencyService.getAllCurrencyData()
if (result.body() != null) {
//currencyLiveData.postValue(result.body())
currencyLiveData.value = result.body()
}
}
}
Method(in MainActivity) to get and update currency list *****
private fun fetchCurrencyRates() {
val currencyService = RetrofitHelper.getInstance().create(CurrencyInterface::class.java)
val repository = CurrencyRepository(currencyService)
val mainViewModel =
ViewModelProvider(this, MainViewModelFactory(repository))[MainViewModel::class.java]
mainViewModel.quotes.observe(this, Observer {
Log.d("AllCurrencyList", it.updated)
})
}
Diwakar Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2