如何使用 WorkManager 在 MVVM 中定期更新来自 Retrofit 的数据?

Wal*_*ann 6 android mvvm kotlin android-livedata android-workmanager

请帮帮我。
我有一个简单的Retrofit-> Repository-> MVVM->Fragment应用程序。
它的作用是从 OpenWeatherApi 提供当前天气。
LiveData在我的ViewModel观察中通过Data Binding.
一切正常。
问题:
现在我想要一个每 20 分钟更新一次天气数据的后台服务。
我试图用WorkManager.
问题是我不知道如何访问我的ViewModel以及如何在LiveData那里更新。
主要问题:
如何使用 WorkManager 在 MVVM 中定期更新来自 Retrofit 的数据?
这是我的代码:
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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

存储库:

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

改造:

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
    }

Run Code Online (Sandbox Code Playgroud)

工作经理:

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()
    }

}

Run Code Online (Sandbox Code Playgroud)