Ad

LiveData,how To Avoid The First Callback When Register Observer

I want to load tasks in a fragment, in fragment's onViewCreated,I register the LiveData observer, in fragment's onResume,I load the task asynchronously, when first enter the fragment,it works fine,but when I navigate to other fragments then back to the task fragment, the callback onChanged() will be called twice.

I know If LiveData already has data set, it will be delivered to the observer, so when back to the task fragment, onChanged will be triggered when registering the observer in onViewCreated, and in onResume, will trigger onChanged the second time, I want to know how to avoid this. I have searched a lot, I know there is an EventWrapper, which can mark the content consumed when onChanged triggered the first time. but I think this approach is too heavy. Sorry for my poor English...

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle 
   savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //...
    mainViewModel = ViewModelProviders.of(getActivity()).get(MainViewModel.class);
    mainViewModel.increaseTaskList.observe(getViewLifecycleOwner(), new 
    Observer<List<Task>>() {
        @Override
        public void onChanged(@Nullable List<Task> tasks) {
            Log.d("ZZZ","data changed,IncreaseTaskListAdapter setData");
            adapter.setData(tasks);
        }
    });
}

@Override
public void onResume() {
    super.onResume();
    mainViewModel.loadIncreasePointTaskList();
}
Ad

Answer

I found a simple solution,check the livedata value before load

@Override
public void onResume() {
    super.onResume();
    if (mainViewModel.increaseTaskList.getValue()==null) {
        Log.d("ZZZ","IncreaseFragment loadTaskAsync");
        mainViewModel.loadIncreasePointTaskList();
    }
}
Ad
source: stackoverflow.com
Ad