我有一个片段,它是活动中的一个选项卡(以及其他几个选项卡)。在片段的一部分中,我想要
observe
我的 Livedata
的 fjViewModel
一次。这是代码:
public class JInPersonFragment extends Fragment {
private FJViewModel fjViewModel;
public static JInPersonFragment newInstance() {return new JInPersonFragment();}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
_InPerson = FragmentJInPersonBinding.inflate(getLayoutInflater());
fjViewModel = new ViewModelProvider(requireActivity()).get( FJViewModel.class);
Observer<Filterj> observer = new Observer<Filterj>() {
@Override
public void onChanged(Filterj filterj)
{//the code keeps coming back inside the onChanged() method
Log.i("jinperson",""+(filterj==null));
....
fjViewModel.getFiltersById(0).removeObserver(this);
}
};
fjViewModel.getFiltersById(0).observe(getViewLifecycleOwner(), observer);
return _InPerson.getRoot();
}
上面的代码显然没有删除观察者。我究竟做错了什么?我现在只懂 Java,无法理解 Kotlin 中的答案。
尝试调用 fjViewModel.getFiltersById(0).removeObservers(getViewLifecycleOwner());
public class JInPersonFragment extends Fragment {
private FJViewModel fjViewModel;
public static JInPersonFragment newInstance() {return new JInPersonFragment();}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
_InPerson = FragmentJInPersonBinding.inflate(getLayoutInflater());
fjViewModel = new ViewModelProvider(requireActivity()).get( FJViewModel.class);
Observer<Filterj> observer = new Observer<Filterj>() {
@Override
public void onChanged(Filterj filterj)
{//the code keeps coming back inside the onChanged() method
Log.i("jinperson",""+(filterj==null));
....
fjViewModel.getFiltersById(0).removeObservers(getViewLifecycleOwner());
}
};
fjViewModel.getFiltersById(0).observe(getViewLifecycleOwner(), observer);
return _InPerson.getRoot();
}