Search code examples
javaandroidviewmodelandroid-roomandroid-livedata

Transformations.distinctUntilChanged not working as intended?


I have multiple instances of same viewmodel in different fragments(scoped to fragments). Whenever I update LiveData in Room, it triggers observable in fragment but it doesn't trigger one instance that should but all of instances(even though the values in others are same). I have thought of a solution as Transformations.distinctUntilChanged but it is not working. My code:

@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
            }
        });
 }

I tried fetching Livedata-Integer from Room and then applying Transformations.distinctUntilChanged() in viewmodel and it worked as intended only triggering one that changed. So I am wondering is it even possible to do this and why are observables triggering even through transformations.


Solution

  • The problem was that I didn't Override equals method in my Entity.class. Therefore it would return completely new object and Transformation.distinctUntilChanged would trigger.