why Viewmodel instance in fragment leaking

Viewed 948

I am using viewmodel and live data to observe changes in a edittext view like below. It's showing me the memory leak while I run the app with leakcanar: Mainactivity.fragviewmodel leaking.

FragViewModel model;

@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    model = new ViewModelProvider(requireActivity()).get(FragViewModel.class);

    final Observer<String> savedTextObserver = newName -> {
        list = MainActivity.quotesDatabaseClass.quoteDao().getQuotes();
        adapter.setData(list);
    };
    model.getTextToSave().observe(requireActivity(), savedTextObserver);
}

@Override
public void onDestroyView() {
    super.onDestroyView();

    fragmentEmojiBinding = null;
    model = null;


}
1 Answers

Using .observe(requireActivity(), savedTextObserver); in a Fragment's onCreateView is never the correct thing: that's saying you want to observe using the Activity's lifecycle, which will continue even if you remove the Fragment or put the Fragment on the back stack.

Instead, you should use .observe(getViewLifecycleOwner(), savedTextObserver); to get the Lifecycle specifically associated with the Fragment's view, which is the correct scope for any Observer that updates your Fragment's UI (such as yoursetAdapter`).

Related