首页 > 解决方案 > 编辑文本并将字符串传递给 ViewModel?

问题描述

我正在创建使用天气 API 的应用程序,我需要从 UI 中的编辑文本到 ViewModel 获取地点名称,并且有 val 从存储库获取方法。在我的情况下如何与 ViewModel 正确通信?LiveData 中有一些魔法咒语还是我需要数据绑定?

视图模型:

class MainViewModel(
private val weatherRepository: WeatherRepository

) : ViewModel() {

val metric: String = "metric"

val currentWeatherByCoordinates by lazyDeferred {
    weatherRepository.getCurrentWeather() }

val forecastByCoordinates by lazyDeferred {
    weatherRepository.getForecast() }

val currentWeatherByCity by lazyDeferred { //This is what I'm writing about
    weatherRepository.getCurrentWeatherByCity("London", metric)
}

}

标签: androidandroid-livedataandroid-viewmodel

解决方案


使用实时数据。在ui中观察一些实时数据method1()->通过method2(city)更改viewmodel中的livedata状态


推荐阅读