我有 2 个实时数据,我将它们作为源添加到中介实时数据中,我从视图模型中公开它以供片段观察。
当任何一个实时数据发生变化时,它都会触发中介实时数据的 onChanged 方法,这意味着我的观察者被触发了两次,我想要将两者结合起来并观察一个只触发一次的流,有什么我在丢失还是我需要为此推出自己的方法?目前我这样做,这会触发两次
为简洁起见删除了一些代码
public CardViewModel(@NonNull Application application , int clicks, String[] cardArgs){
sentenceRepository = new SentenceRepository(application);
cards = Transformations.switchMap(search, mySearch -> sentenceRepository.searchLiveCardListByWordTypeAndWordDescriptionAndSearchWord(cardArgs[0],cardArgs[1],mySearch));
groupRepository = new GroupRepository(application);
groups = groupRepository.getGroupsByWordDescriptionAndWordType(cardArgs[0],cardArgs[1]);
sentencesAndGroups = new MediatorLiveData<>();
sentencesAndGroups.addSource(cards, sentences -> {
Log.d(TAG,"addSource cards");
sentencesAndGroups.setValue(combineLatest(sentences, groups.getValue()));
});
sentencesAndGroups.addSource(groups, groupsWithSentences -> {
Log.d(TAG,"addSource groups");
sentencesAndGroups.setValue(combineLatest(cards.getValue(), groupsWithSentences));
});
}
private List<Visitable> combineLatest(List<Sentence> sentenceList, List<GroupsWithSentences> groupsWithSentences) {
List<Visitable> visitableList = new ArrayList<>();
if (sentenceList != null){
visitableList.addAll(sentenceList);
}
if (groupsWithSentences != null){
visitableList.addAll(groupsWithSentences);
}
return visitableList;
}
有什么帮助吗?