为什么片段中的 Viewmodel 实例泄漏 [英] why Viewmodel instance in fragment leaking

查看:30
本文介绍了为什么片段中的 Viewmodel 实例泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用视图模型和实时数据来观察如下所示的编辑文本视图中的变化.当我使用leakcanar 运行应用程序时,它向我显示了内存泄漏:Mainactivity.fragviewmodel 泄漏.

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;


}

推荐答案

Using .observe(requireActivity(), savedTextObserver); 在 Fragment 的 onCreateView 中永远是不正确的事情:也就是说,您想使用 Activity 的生命周期进行观察,即使您删除 Fragment 或将 Fragment 放在后堆栈中,该生命周期也会继续.

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.

相反,您应该使用 .observe(getViewLifecycleOwner(), savedTextObserver); 来获取与 Fragment 视图特别关联的生命周期,这是更新您的任何观察者的正确范围Fragment 的 UI(比如你的setAdapter`).

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`).

这篇关于为什么片段中的 Viewmodel 实例泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆