1

I'm learning how android architecture components work. For that, I'm trying to build a weather application. I want to get the location from the device and after that fetch weather at that location.

For this, I'm using Two LiveData Objects, One for location and another for weather. After receiving the location update I'm setting another observer for weather inside the location LiveData observer. Here is the code for same:

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

        }
    });

Everything works as expected, but is this the correct way to do this? Is it okay to have nested observables or there is a better way?

shyam
  • 596
  • 9
  • 18
  • 1
    Considering each time `location` changes, `loadCurrentWeather()` is called and previous subscriptions are not removed; no this is not the correct way and you should be using `Transformations.switchMap`. – EpicPandaForce Feb 07 '19 at 17:28

0 Answers0