【发布时间】:2023-04-03 21:29:01
【问题描述】:
我有一个数据库,其中包含英制和公制单位的天气数据。现在,我创建了两个不同的类,它们作为模型从数据库中获取数据。 CurrentWeatherMetric 只有公制列,CurrentWeatherImperial 只有英制字段。
由于我使用的是 MVVM 架构模式,ViewModel 通过调用 ViewModel 中的函数getData(Unit.METRIC) 为我提供了这些数据,其中Unit 是我用来区分数据的enum class。
问题就出现在这里。 我的 viewModel 看起来像:
class WeatherViewModel(
private val weatherRepository: WeatherRepositoryImpl
) : ViewModel() {
lateinit var currentWeather: LiveData<CurrentWeather>
lateinit var forecastWeather: LiveData<List<ForecastWeather>>
fun getValuesOfUnit(unit: Unit) {
currentWeather = when (unit) {
Unit.IMPERIAL->weatherRepository.getCurrentWeatherImperial()
Unit.METRIC->weatherRepository.getCurrentWeatherMetric()
}
getWeather()
}
private fun getWeather() {
viewModelScope.launch {
try {
weatherRepository.getWeather()
} catch (e: IOException) {
}
}
}
}
如您所见,lateinit var currentWeather: LiveData<CurrentWeather>,
我不得不创建另一个类来存储带有单位的查询数据。我这样做是为了可以轻松地用它实现数据绑定。但我觉得这是一种非常错误的做事方式,因此我提出了这个问题。如何摆脱 lateinit 变量并实现数据绑定以适应任何数据。
在我当前的数据绑定布局中,我的数据字段为:
<data>
<variable
name="viewModel"
type="com.mythio.weather.ui.WeatherViewModel" />
</data>
我通过以下方式绑定到视图:
app:someattribute="@{viewModel.currentWeather.temperature}"
如果问题标题对我所问的内容有点意义,或者似乎具有误导性,请随时对其进行编辑以使其成为更好的问题。
【问题讨论】:
-
尽管使用了 lateinit,您也可以使用
MutableLiveData在同一行中使用类似val data: LiveData<> = MutableLiveData()的声明对其进行初始化。虽然 UI 绑定对我来说似乎没问题。 -
那么我实现其余代码的方式还可以吗?
-
是的,我认为遵循 MVVM 并从存储库获取数据是最佳实践。推荐的方法是将您的 ViewModel 绑定到 UI 并从存储库中获取数据,这始终是您数据的单一真实来源。
-
好的,谢谢!如果你写一个答案,我会把它标记为正确
-
但我并没有帮助你获得这样的声誉。
标签: android kotlin mvvm android-room android-livedata