Reputation:
Scenario I have Spinner and RecyclerView. The spinner has three different options VIP Users ,New Users , High Score Users. In 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;}
And in myFragment,
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
}
}
Everything went fine. But When I select another options on Spinner. Example when I change VIP user to High Score User, livdata observe old data too. If user1,2,3 are VIP users and user4,5 are high score users, all 5 user are displaying in High score users instead of showing user4,5 only.
So I want to delete previous data from livedata when Spinner Selection change. Is there some way to accomplish this?
Upvotes: 0
Views: 130
Reputation: 1609
what I would use is switchMap
in livedata. So basically I would have something like this:
MutableLiveData userTypeLiveData = MutableLiveData<Int>;
LiveData userLiveData = Transformations.switchMap(userTypeLiveData, userType ->
myRepo.getInstance().getUsersByType(userType);
)
void selectUser(int userType) {
this.userTypeLiveData.setValue(userType);
}
And I would add switch in Repository class
Upvotes: 1