LiveData is Observing on tab change

I am facing a problem with using LiveData.

Scenario…

I have a BottomNavigationView with 4 tabs. Forum,Message,Users,Account. Each connects with the ViewPager fragment. Each fragment has its own ViewModel, Model, and Repository. I load data from the database to Users Fragment’s RecyclerView. It works fine. But when I swipe my viewPager to another tab, my User list gets doubled. Actually, it loads only the last observed item twice. For example.. if user5 is the last item when retrieving when I come back from another tab fragment, there are two user5 on the list. More times I change my tabs, many times of the last item get observed.

This is my Users_Fragment.class

public class Users_Fragment extends Fragment{    private ArrayList<Users> user_info_list;    private UserFragment_ViewModel userFragment_viewModel ;     @Override    public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);     }     @Override    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {      mainView = inflater.inflate(R.layout.user_fragment, container ,false);      userFragment_viewModel = new ViewModelProvider(this).get(UserFragment_ViewModel.class);       user_info_list = new ArrayList<>();       initiate();      fetchUsers();      return mainView;    }       private void initiate(){        // declare RecyclerView and some status checking code    }     private void fetchUsers() {      // fetch user to recyclerview      user_info_list.clear();      recyclerView.setHasFixedSize(true);      LinearLayoutManager layoutManager                 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);      recyclerView.setLayoutManager(layoutManager);               userFragment_viewModel.initiate(); // start retrieving from database with repository and load it      userFragment_viewModel.getPeople_list()                            .removeObservers(getViewLifecycleOwner());       userFragment_viewModel.getPeople_list()                            .observe(getViewLifecycleOwner(), usermodel -> {                               user_info_list.add(usermodel);                               userAdapter.notifyDataSetChanged();                            });      userAdapter = new UserAdapter(getContext(),user_info_list);      recyclerView.setAdapter(userAdapter);   } } 

And this is my UserFragment_ViewModel.class

public class UserFragment_ViewModel extends ViewModel {         private LiveData<UserModel> people_list_info ;    public void initiate() {     people_list_info = Users.getInstance().getUser_live_data();   }    public LiveData<UserModel> getPeople_list() {     return people_list_info;   } } 

How to solve this? Why my last observe item get Observed again and again as I change my tab?

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.