View Model keeps creating instance of Live Data

前端 未结 5 1408
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 16:47

I created the instance of View Model in onCreate method of an activity.

    ticketViewModel = ViewModelProviders.of(this).get(TicketViewModel.cl         


        
5条回答
  •  [愿得一人]
    2021-01-18 17:35

    You only need to call the observe once, I prefer to do it in onResume and then call removeObserver in onPause:

    Adds the given observer to the observers list

    You keep adding listeners to the data so you get multiple callbacks.

    Edit:
    I took an existing code sample of mine for a Fragment and renamed everything (I hope), there's no example here for setting the data into the ViewModel but it should be ticketViewModel.AddTicket(id); in your case.

    public class ListFragment extends Fragment {
    
        private MyViewModel viewModel;
        private MyRecyclerViewAdapter recyclerViewAdapter;
        private Observer> dataObserver;
        private RecyclerView recyclerView;
    
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
            initRecyclerView(rootView, getContext());
            initObservers();
    
            return rootView;
        }
    
        private void initRecyclerView(View rootView, Context context) {
            recyclerViewAdapter = new MyRecyclerViewAdapter(context);
            recyclerView = rootView.findViewById(R.id.recycler_view);
            recyclerView.setAdapter(recyclerViewAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
            recyclerView.setLayoutManager(linearLayoutManager);
            recyclerView.addItemDecoration(new DividerNoLastItemDecoration());
        }
    
        private void initObservers() {
            dataObserver = new Observer>() {
                @Override
                public void onChanged(@Nullable final List data) {
                    recyclerViewAdapter.setData(data);
                }
            };
        }
    
        @Override
        public void onResume() {
            super.onResume();
            initViewModel();
        }
    
        private void initViewModel() {
            FragmentActivity activity = getActivity();
            if (activity != null) {
                viewModel = ViewModelProviders.of(activity).get(MyViewModel.class);
                viewModel.getData().observe(activity, dataObserver);
            }
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if (viewModel != null) {
                viewModel.getData().removeObserver(dataObserver);
                viewModel = null;
            }
        }
    
    }
    

提交回复
热议问题