我正在使用带有MVVM +存储库+带有改造的NodeJS后端结构的应用程序。我面临的问题如下:
调用ViewModel的活动代码
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
runBlocking {
viewModel.setQueryToRepository(query)
}
活动的视图模型可更新存储库中的城市
suspend fun setQueryToRepository(city: String){
weatherRepository.setCity(city)
}
存储库内部的实现
private var city: String = ""
override suspend fun setCity(city: String){
this.city = city
Log.d("data", "city: ${this.city}")
getSearchedWeather()
}
override suspend fun getSearchedWeather(): LiveData<out CurrentWeatherEntity> {
return withContext(Dispatchers.IO) {
if (city == ""){
return@withContext currentWeatherDAO.getCurrentWeatherFromDB(34.04563903808594,-118.24163818359375)
}
val (lat, lng) = getLocationFromAddress(city)
Log.d("data","lat: $lat, lon: $lng, city: $city")
initFetchSearchedWeatherData(lat, lng, city)
Log.d("data", "return value is: ${currentWeatherDAO.getByCity(city)}")
return@withContext currentWeatherDAO.getCurrentWeatherFromDB(1.352083, 103.819836)
}
}
initFetchSearchedWeatherData(lat,lng,city)函数决定是否进行提取(基于数据的新鲜度),如果是,它将调用改造并更新其Livedata,我在存储库的init函数中观察到的是这样的。 / p>
init{
weatherNetworkDataSource.downloadedCurrentWeather.observeForever{ newCurrentWeather ->
Log.d("data", "changed data is, lat: ${newCurrentWeather.location.latitude}, lng: ${newCurrentWeather.location.longitude}")
persistFetchedCurrentWeather(newCurrentWeather)
}
persistFetchedCurrentWeather()函数只是将数据向上插入数据库的current_weather表中。
private fun persistFetchedCurrentWeather(fetchedWeather: CurrentWeatherEntity){
Log.d("data", "data in persist is, lat: ${fetchedWeather.location.latitude}, lng: ${fetchedWeather.location.longitude}")
GlobalScope.launch(Dispatchers.IO) {
currentWeatherDAO.upsertCurrentWeatherData(fetchedWeather)
val data = currentWeatherDAO.getAllData()
data.map {
Log.d("data", "entry is ${it.location}")
}
}
}
所以我最终从表返回Livedata为:
return@withContext currentWeatherDAO.getWeatherByCity(city)
为方便起见,我将总结存储库中的功能。
我从其视图模型观察Livedata的片段
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)
.get(WeatherSearchResultViewModel::class.java)
bindUI()
val searchedWeather = viewModel.getDataFromRepository.await()
searchedWeather.observe(viewLifecycleOwner, Observer {
if (it == null) {
group_ready.visibility = View.GONE
group_loading.visibility = View.VISIBLE
return@Observer
}
// Update UI here
})
以及Fragment的视图模型,将其作为Livedata从存储库的getSearchedWeather(上面添加的代码)中以Livedata的形式返回
val getDataFromRepository by lazyDeferred {
weatherRepository.getSearchedWeather()
}