首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Transformations.distinctUntilChanged没有按预期工作?

Transformations.distinctUntilChanged没有按预期工作?
EN

Stack Overflow用户
提问于 2020-04-02 05:24:39
回答 1查看 1.8K关注 0票数 0

我在不同的片段中有相同视图模型的多个实例(作用域为片段)。每当我在Room中更新LiveData时,它都会在片段中触发可观察到的实例,但它不会触发一个应该触发的实例,而是所有的实例(尽管其他实例中的值是相同的)。我认为解决方案是Transformations.distinctUntilChanged,但它不起作用。我的代码:

代码语言:javascript
复制
@Dao
public interface PlayerDao {
  @Query("SELECT * from player_table WHERE id_playera=:id")
  LiveData<PlayerEntity> getPlayer(final int id);
 }

public class PlayerRepository {
  public LiveData<PlayerEntity> getPlayer(final int id) {
        return playerDao.getPlayer(id);
    }
 }

public class PlayerViewModel extends AndroidViewModel {
  public LiveData<PlayerEntity> getPlayer(final int id) {
        return Transformations.distinctUntilChanged(repository.getPlayer(id));
    }
 }

 @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        playerViewModel = new ViewModelProvider(this).get(PlayerViewModel.class);
        playerViewModel.getPlayer(redniBrojPlayera).observe(getViewLifecycleOwner(),
        newObserver<PlayerEntity>() {
            @Override
            public void onChanged(PlayerEntity playerEntity) {
                //triggers UI
            }
        });
 }

我试着从Room中获取Livedata-Integer,然后在视图模型中应用Transformations.distinctUntilChanged(),它的工作原理是只触发一个更改的。所以,我想知道,这是否可能做到这一点,为什么可观测的触发甚至通过转换。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-02 15:34:28

问题是,在我的Entity.class中,我没有覆盖等于方法。因此,它将返回全新的对象,Transformation.distinctUntilChanged将触发。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60984722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档