如何防止实时日期重复出现在从另一个片段上按回和重新调用

问题描述 投票:0回答:1

您好,关于具有视图模型和导航组件的实时数据存在两个问题,首先是当我从具有实时数据的片段A转到片段B,然后从B移到A时,我列表中的数据被复制了,另一个问题是我在制作片段后再次调用viewModel.loadList(),并且过滤数据的事件也被复制了

这是我的视图模型

  public class HomeViewModel extends ViewModel {
  MutableLiveData<ArrayList<HomeResponseModel>> homeLiveData = new MutableLiveData<>();
    ArrayList<HomeResponseModel> homeList = new ArrayList<>();
     public MutableLiveData<ArrayList<HomeResponseModel>> geHomeList(HomeRequestModel homeRequestModel, Context context, ApiInterface apiInterface, LottieAnimationView lottieAnimationView) {
            if (homeLiveData == null) {
                homeLiveData = new MutableLiveData<ArrayList<HomeResponseModel>>();
                loadHomeList(homeRequestModel);

            }
            return homeLiveData;
        }
  public void loadHomeList(HomeRequestModel homeRequestModel) {

            Call<List<HomeResponseModel>> call = apiInterface.getHomeList(homeRequestModel, );
            call.enqueue(new Callback<List<HomeResponseModel>>() {
                @Override
                public void onResponse(Call<List<HomeResponseModel>> call, Response<List<HomeResponseModel>> response) {

                    if (response.isSuccessful()) {
                        homeList.addAll(response.body());
                        homeLiveData.setValue(homeList);
                    }

                }

                @Override
                public void onFailure(Call<List<HomeResponseModel>> call, Throwable t) {

                }
            });


    }

我在onCreateView中的观察者

viewModel.geHomeList(homeRequestModel).observe(getViewLifecycleOwner(), new Observer<ArrayList<HomeResponseModel>>() {
            @Override
            public void onChanged(ArrayList<HomeResponseModel> homeResponse) {


                homeResponseModels.addAll(homeResponse);
                homeAdapter.notifyDataSetChanged();
            }
        });



        }

我在过滤事件后如何调用加载方法

            viewModel.loadHomeList(homeRequestModel);
android navigation fragment viewmodel android-livedata
1个回答
1
投票

在添加新模型之前清除列表:

© www.soinside.com 2019 - 2024. All rights reserved.