Android LiveData creating multiple observers in fragment

android-livedata observer called multiple times
observe livedata in fragment
android room, livedata
livedata observer not called
livedata observeforever
viewlifecycleowner
fragment observer android
singleliveevent

After searching lots of other SO questions and reading articles I'm still stuck as to why my implementation does not seem to perform as other examples.

I've read that it's recommended to use getViewLifecycleOwner() when registering any LiveData observers inside of a fragment to handle the lifecycle of the fragment correctly.

However, inside my fragment OnActivityCreated method (which gets called twice when the fragment is shown on the screen) I seem to get different LifecycleOwner objects from the call to getViewLifecycleOwner() which I beleive is the reason I'm getting multiple observers registered to my LiveData object.

How do I prevent this from happening / what am I doing wrong?

I've added lots of logging to the code as below:

MainActivity

   public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment, new LiveDataTestFragment())
                    .commit();

            Log.d("debugger2", "Activity: " + this.hashCode());
        }
    }

LiveDataTestFragment

public class LiveDataTestFragment extends Fragment {

    private LiveDataViewModel viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_live_data_test, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        viewModel = ViewModelProviders.of(getActivity()).get(LiveDataViewModel.class);

        Log.d("debugger2", "ViewModel: " + viewModel.hashCode());

        LiveData<String> liveData = viewModel.getLiveData();
        Log.d("debugger2", "LiveData: " + liveData.hashCode());

        LifecycleOwner lifecycleOwner = getViewLifecycleOwner();
        Log.d("debugger2", "LifeCycleOwner: " + lifecycleOwner.hashCode());

        liveData.observe(lifecycleOwner, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d("debugger2", "observer hash: " + this.hashCode());
            }
        });
    }
}

Logcat:

D: Activity: 242098714
D: ViewModel: 149122972
D: LiveData: 58736037
D: LifeCycleOwner: 50378106
D: ViewModel: 149122972
D: LiveData: 58736037
D: LifeCycleOwner: 245135826
D: observer hash: 204470220
D: observer hash: 226765595
new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d("debugger2", "observer hash: " + this.hashCode());
            }
        }

May be this portion of your observer is responsible to create multiple hashCode() You can create this observer just for a single time and call it multiple times if you need using the following code:

private Observer<String> singleObserver = Observer<String>() {
                @Override
                public void onChanged(String s) {
                    Log.d("debugger2", "observer hash: " + this.hashCode());
                }
}

and use it like:

// your previous code
LiveData<String> liveData = viewModel.getLiveData();
liveData.observe(lifecycleOwner, singleObserver);
// rest of your code

Hope it will work.

LiveData Overview, Leaking LiveData observers in Fragments observers being active at the same time and same code from onChanged() being executed multiple times. Creating ViewModel's dependencies after every configuration change The latest posts from Android Professionals and Google Developer Experts. Summary: Multiple LiveData Observers are being triggered in a Fragment after navigating to a new Fragment, popping the new Fragment, and returning to the original Fragment. Details : The architecture consists of MainActivity that hosts a HomeFragment as the start destination in the MainActivity's navigation graph .

I've figured out the issue. Thanks for the answers regardless!

I'll put the issue here even though it's unlikely anyone else will do what I did!

My activity_main.xml contained

<fragment
    android:name="com.test.livedatatestapp.LiveDataTestFragment"
    android:id="@+id/fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

which was creating an instance of the Fragment class, which I was then immediately replacing inside MainActivity by replacing the Fragment, hence the duplicates...

5 common mistakes when using Architecture Components, Google introduced Android architecture components which are basically a was triggering LiveData multiple data on the same Observer. If the user navigates to FragmentB again and presses back to visit FragmetnA, the LiveData observer was triggered thrice and it continued to increase. Debugging Approach. The initial thought was somehow(due to Fragment going though lifecycle) ViewModel was triggering LiveData multiple data on the same Observer. We added the following log to ensure this is the case:

You need to remove the observer before making an observer.

Observe LiveData from ViewModel in Fragment - Noteworthy, object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment. Now that we know how it works, let’s say we have a livedata with multiple observers and three fragments — F1, F2, and F3 — which are in the stack. All three fragments share a ViewModel and

Necessity of ViewModel and Difference Between MutableLiveData , for observing changes in the view and updating the view when it is ACTIVE. I have multiple *LiveData* *Observers* that are being triggered in a Fragment after navigating to a new Fragment, popping the new Fragment, and returning to the original Fragment. *Details*: The architecture consists of *MainActivity* that hosts a *HomeFragment* as the *start destination* in the MainActivity's *navigation graph*.

Android LiveData, I have multiple LiveData Observers that are being triggered in a instead of the fragment instance? android/architecture-samples#675. Open. Work with LiveData objects. Create LiveData objects. LiveData is a wrapper that can be used with any data, including objects that implement Collections , such as List . A Kotlin. class NameViewModel : ViewModel() { // Create a LiveData with a String val currentName: MutableLiveData<String> by

Fragments create new instances of Observers after , It's mostly used to deliver data from the view model to fragments and activities in let's say we have a livedata with multiple observers and three fragments — F1, need to create a class with the name Event to wrap the data that the livedata is​  Architecture components are now a big thing for Android developers. LiveData is one of the major components that we want to look in detail here. In my blog above, it covers ViewModels and LiveData…

Comments
  • It's creating multiple observers because, you're providing multiple observers using new Observer inside observe() method. Create global variable for observer and add it your observe method. Also make sure you remove observer when fragment destroyed.
  • That's not how it's set up in google samples: link or link for example
  • That's not how it's set up in google samples: link or link for example
  • Please read the document again carefully. I am sharing a code snippet from LiveData and Observer into the edited version of my answer. check this link for documentation [developer.android.com/topic/libraries/architecture/livedata ]