嵌套LivaData实现

时间:2019-02-02 14:30:41

标签: android android-architecture-components android-livedata android-mvvm

我正在学习android架构组件的工作方式。为此,我正在尝试构建一个天气应用程序。 我想从设备获取位置,然后获取该位置的天气。

为此,我使用了两个LiveData对象,一个用于定位,另一个用于天气。收到位置更新后,我将在位置LiveData观察器内设置另一个天气观察器。这是相同的代码:

LiveData<LocationData> locationDataLiveData = LocationService.getLocation(MainActivity.this);
    locationDataLiveData.observe(this, location -> {
        if (location != null) {
            WeatherViewModelFactory factory = new WeatherViewModelFactory(location.getLatitude(),
                    location.getLongitude());
            WeatherViewModel viewModel = ViewModelProviders.of(mainActivity, factory).get(WeatherViewModel.class);

            viewModel.loadCurrentWeather().observe(MainActivity.this, currentWeather -> {
                temp.setText(currentWeather.getCountry() + " " + currentWeather.getTemp());
            });

        }
    });

一切正常,但这是正确的方法吗?嵌套可观察项可以吗,还是有更好的方法?

0 个答案:

没有答案