Search code examples
javaandroidfragmentviewmodelandroid-livedata

Changing LiveData in Activity doesn't notify observer in child Fragment


I'm trying to update LiveData object in activity that hosts a fragment and then I want to update the fragment's UI after observing it. The problem is the fragment's ui only updates when fragment is restarted. What can I do to achievie real-time update of Ui in fragment every time the data changes in activity?

// Activity code:

   transactionViewModel = ViewModelProviders.of(this, providerFactory).get(TransactionViewModel.class);  
transactionViewModel.getUserValues();

/// Fragment:

    transactionViewModel = ViewModelProviders.of(getActivity(), providerFactory).get(TransactionViewModel.class); 
viewModel.userValues.observe(getActivity(), userValues -> {  if(userValues.data != null){}//update the ui }

Solution

  • To achievie "real-time update of Ui" i sugesst using data-binding.

    In your code, I think you are observing a deferent reference of viewModel.

    Try observing after casting your activity(am using kotlin here):

            val myActivity = (requireActivity() as MainActivity)
            myActivity.transactionViewModel.viewModel.userValues.observe(getActivity(), userValues -> { 
            if(userValues.data != null){}//update the ui }