Md Jubayer
Md Jubayer

Reputation: 272

onChanged method of livedata observe called multiple times

In my fragment layout file I have a spinner:

                <android.support.v7.widget.AppCompatSpinner
                android:id="@+id/sp_week"
                android:layout_width="150dp"
                android:layout_height="50dp"
                android:entries="@array/week"
                android:paddingLeft="20dp"
                android:selectedItemPosition="@={TimeSheetFragViewModel.selectedWeek}">

And in TimeSheetFragViewModel class I declared the selectedWeek like this:

    public MutableLiveData<Integer> selectedWeek = new MutableLiveData<>();

public int getSelectedWeek() {

    if(selectedWeek.getValue() == null) return 0;
    return selectedWeek.getValue();
}

public void setSelectedWeek(int value) {
    selectedWeek.setValue(value);
}

In My Fragment I put observer in onActivityCreated for this live data like this:

       timeSheetFragViewModel.selectedWeek.observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer integer) {

            Log.d("DEBUG", "its called");

        }
    });

when the fragment is first time loaded the onChanged method called one time. Which I think is okay. However, when i rotate the screen the onChanged method called two times. I need explanation why it is happening.

Upvotes: 1

Views: 1466

Answers (1)

Sanlok Lee
Sanlok Lee

Reputation: 3494

That is because the LiveData observers are removed in onDestroy(). You should note that onActivityCreated() can be called multiple times without onDestroy() being called. In this scenario every time onActivityCreate() is called, the fragment will attach a new observer instance to the LiveData without previous observers being removed.

Therefore, you must either observe LiveData in the fragment.onCreate()--which is not really practical, or use getViewLifecycleOwner() to get a more reasonable LifecycleOwner instance.

For instance, the correct way to observe in onActivityCreated() is:

timeSheetFragViewModel.selectedWeek.observe(getViewLifecycleOwner(), new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable Integer integer) {
        ...
    }
});

Upvotes: 2

Related Questions