【问题标题】:Delete all liveData and Observer on Spinner selected删除选定 Spinner 上的所有 liveData 和 Observer
【发布时间】:2020-06-19 05:47:42
【问题描述】:

场景 我有 Spinner 和 RecyclerView。微调器具有三个不同的选项VIP 用户新用户高分用户。在 myViewModel 中,

private liveData<ArrayList<User>> userList;
public void init(int position){
switch (position){
  case 0: 
    userList = myRepo.getInstance().getVipUser();
  break;

  case 1:
  userList = myRepo.getInstance().getNewUser();
 break;

 case 2:
 userList = myRepo.getInstance().getHScoreUser();
 break;
 }}

 public LiveData<ArrayList<User>> getUserList(){return userList;}

在我的片段中,

spinner.setOnItemSelectedListener(this);

 public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
myViewModel.getUserList().removeObserver(getViewLifeCycleOwner ());
myViewModel.init(pos);

myViewModel.getUserList().observe(getViewLifeCycleOwner(), 
 userList->{
      //Attach userList to RecyclerView
          }
 }  

一切都很顺利。但是当我在 Spinner 上选择另一个选项时。例如,当我将 VIP 用户 更改为 高分用户 时,livdata 也会观察旧数据。如果 user1,2,3 是 VIP 用户,user4,5 是高分用户,则所有 5 个用户都显示在高分用户中,而不是只显示 user4,5。

所以我想在 Spinner Selection 更改时从 livedata 中删除以前的数据。有没有办法做到这一点?

【问题讨论】:

    标签: java android android-livedata android-architecture-components


    【解决方案1】:

    我会在 livedata 中使用 switchMap。所以基本上我会有这样的东西:

    MutableLiveData userTypeLiveData = MutableLiveData<Int>;
    LiveData userLiveData = Transformations.switchMap(userTypeLiveData, userType ->
    
        myRepo.getInstance().getUsersByType(userType);
    )
    
    void selectUser(int userType) {
         this.userTypeLiveData.setValue(userType);
    }
    

    我会在 Repository 类中添加开关

    【讨论】:

    • userIdLiveData 是什么类型的 LiveData?
    • 对不起,我编辑了答案的名称,并没有到处更改名称,现在看:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多