android – How to update data from Retrofit periodically in MVVM using WorkManager?-ThrowExceptions

Exception or error:

Help me out please.
I have a simpe Retrofit->Repository->MVVM->Fragment app.
What it does is provides current weather from OpenWeatherApi.
I have my LiveData in my ViewModel observed via Data Binding.
It all works fine.
Issue:
Now I want a background service which updates weather data every 20 minutes.
Im trying to implement this with WorkManager.
And the problem is that I don’t know how to access my ViewModel and how to update LiveData there.
Main question:
How can I update data from Retrofit periodically in MVVM using WorkManager?
Here is my code:
ViewModel:

class CurrentViewModel(application: Application) : AndroidViewModel(application) {
        val repo = mRepository.getInstance(application)
        val context = application
        //This is data i am observing by Data Binding
        var currentWeather: LiveData<CurrentWeather>? = repo.getCurrentWeather()
        //This method does not seem work when called explicitly btw.
        fun updateWeather(){
            currentWeather = repo.getCurrentWeather()
        }
    }

Repository:

class mRepository private constructor(private val context: Context) {
    val retrofitClient = RetrofitResponseProvider()
    //From here I receive LiveData
    fun getCurrentWeather(): LiveData<CurrentWeather>? {
        return retrofitClient.getCurrentWeather()
    }
}

Retrofit:

class RetrofitResponseProvider {
    fun getCurrentWeather(): LiveData<CurrentWeather>? {
        val currentWeatherLivedata: MutableLiveData<CurrentWeather> by lazy {
            MutableLiveData<CurrentWeather>()
        }
        val forecast = RetrofitClientInstanceProvider.getRetrofitInstance()?.create(WeatherApiService::class.java)
        val call = forecast?.getCurrentWeather()
        call?.enqueue(object : Callback<CurrentWeather> {
            override fun onResponse(call: Call<CurrentWeather>, response: Response<CurrentWeather>) {
                currentWeatherLivedata.value = response.body()
            }
            override fun onFailure(call: Call<CurrentWeather>, t: Throwable) {
            }
        })
        return currentWeatherLivedata
    }

WorkManager:

class MyWorker(val context: Context, val workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    override fun doWork(): Result {
        //This is what I want it to do somehow
        viewModel.updateWeatherData()
        return Result.success()
    }

}

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *