今天搞一个自定义DialogFragment,使用了architecture架构,这里出现了内存泄漏,上代码:
MutableLiveData<List<String>> mlist = new MutableLiveData<>();
mlist.observe((LifecycleOwner) getActivity(), new Observer<List<String>>() {
@Override
public void onChanged(@Nullable List<String> strings) {
adapter.replace(strings);
}
});
报的是实现lifecycle接口的类内存泄漏,也就是宿主Activity了,我在这里使用了MutableLiveData来处理list发生的变化,这里需要在当前页面被finish的时候把对宿主Activity的引用释放掉,所以需要加上这么一行代码
@Override
public void onDestroy() {
if (disposable != null) {
//此处可以忽略
disposable.dispose();
}
if(mlist != null){
mlist.removeObservers((LifecycleOwner) getActivity());
}
super.onDestroy();
}