Search code examples
androidmvvmandroid-architecture-componentsandroid-livedataandroid-jetpack

How to implement nested live data?


How to implement nested live data in android : I need to pass the serverMovies to second level of Live data

Is this possible ?

   activityViewModel.getAllMovies().observe(this, new Observer<List<Movie>>() {
                @Override
                public void onChanged(List<Movie> serverMovies) {
                    Log.d("",serverMovies+"");

                    activityViewModel.insertMoviesIntoLocalDatabase(serverMovies).observe(this, new Observer<List<Movie>>() {
                        @Override
                        public void onChanged(@Nullable List<Movie> movies) {
                            Log.d("",movies+"");
                            /*contactArrayList.clear();
                            contactArrayList.addAll(contacts);
                            contactsAdapter.notifyDataSetChanged();*/

                        }
                    });
                }


     });

Solution

  • You need to add a Mediator Live Data that reacts to changes in the movies live data.

    Something like this,

    LiveData<List<Movies>> moviesLiveData = getAllMovies();
    MediatorLiveData mediatorLiveData = new MediatorLiveData<>();
    mediatorLiveData.addSource(moviesLiveData, value -> mediatorLiveData.setValue(value));
    

    So when the value of the original live data changed the value of the mediator live data changes too, then you can observe it anyway you want.