Skip to content

Instantly share code, notes, and snippets.

@florina-muntenescu
Last active February 27, 2023 06:04
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save florina-muntenescu/fea9431d0151ce0afd2f5a0b8834a6c7 to your computer and use it in GitHub Desktop.
Save florina-muntenescu/fea9431d0151ce0afd2f5a0b8834a6c7 to your computer and use it in GitHub Desktop.
Avoid false positives notifications for observable queries - https://medium.com/google-developers/7-pro-tips-for-room-fbadea4bfbd1

Avoid false positive notifications for observable queries

For why this happens and more details check out 7 Pro-tips for Room!

/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.observability.persistence.gist
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.Observer
/**
* LiveData that propagates only distinct emissions.
*/
fun <T> LiveData<T>.getDistinct(): LiveData<T> {
val distinctLiveData = MediatorLiveData<T>()
distinctLiveData.addSource(this, object : Observer<T> {
private var initialized = false
private var lastObj: T? = null
override fun onChanged(obj: T?) {
if (!initialized) {
initialized = true
lastObj = obj
distinctLiveData.postValue(lastObj)
} else if ((obj == null && lastObj != null) || obj != lastObj) {
lastObj = obj
distinctLiveData.postValue(lastObj)
}
}
})
return distinctLiveData
}
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.observability.persistence.gist
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Query
import com.example.android.observability.persistence.User
import io.reactivex.Flowable
/**
* Data Access Object for the users table.
*/
@Dao
abstract class UserDao {
/**
* Get a user by id.
* @return the user from the table with a specific id.
*/
@Query("SELECT * FROM Users WHERE userid = :id")
protected abstract fun getUserById(id: String): LiveData<User>
fun getUserByIdDistinctLiveData(id: String): LiveData<User> = getUserById(id).getDistinct()
/**
* Get a user by id.
* @return the user from the table with a specific id.
*/
@Query("SELECT * FROM Users WHERE userid = :id")
protected abstract fun getUserByIdFlowable(id: String): Flowable<User>
fun getUserByIdDistinctFlowable(id: String): Flowable<User> =
getUserByIdFlowable(id)
.distinctUntilChanged()
}
@gabin8
Copy link

gabin8 commented Mar 20, 2018

how it looks like in Java?

@or-dvir
Copy link

or-dvir commented May 26, 2018

i tried converting it to java but it doesnt seem to work.
what am i doing wrong?

public LiveData<List<TvShowEntity>> getAllDistinct()
    {
        final MediatorLiveData<List<TvShowEntity>> mld = new MediatorLiveData<>();

        mld.addSource(getAll(), new Observer<List<TvShowEntity>>()
        {
            boolean isInitialized = false;
            List<TvShowEntity> lastObject = null;

            @Override
            public void onChanged(@Nullable List<TvShowEntity> tvShowEntities)
            {
                if(isInitialized == false)
                {
                    isInitialized = true;
                    lastObject = tvShowEntities;

                    mld.postValue(lastObject);
                }

                else if ((tvShowEntities == null && lastObject != null) ||
                         tvShowEntities != lastObject)
                {
                    lastObject = tvShowEntities;
                    mld.postValue(lastObject);
                }
            }
        });

        return mld;
    }

@vipulyaara
Copy link

Does it keep another copy of the result in memory? Is there an alternative if there are large data sets that need to be queried and we don't want to keep their copies?

@Smurph82
Copy link

Smurph82 commented Jun 4, 2019

For java create an abstract class as follows

public abstract class DistinctLiveData<ResultType> {

    private final MediatorLiveData<ResultType> result = new MediatorLiveData<>();

    public DistinctLiveData() {
        final LiveData<ResultType> data = load();
        result.addSource(data, new Observer<ResultType>() {
            boolean initialized = false;
            ResultType lastObj;

            @Override
            public void onChanged(ResultType obj) {
                if (!initialized) {
                    initialized = true;
                    lastObj = obj;
                    result.postValue(lastObj);
                } else if ((obj == null && lastObj != null) ||
                        !DistinctLiveData.this.equals(obj, lastObj)) {
                    lastObj = obj;
                    result.postValue(lastObj);
                }
            }
        });
    }

    protected boolean equals(ResultType newObj, ResultType lastObj) { return newObj == lastObj; }

    protected abstract LiveData<ResultType> load();

    public LiveData<ResultType> asLiveData() { return result; }
}

To be used as follows

@Dao
public abstract class PersonDao {
...
    @Query("SELECT * FROM Person WHERE id = :id")
    protected abstract LiveData<Person> getPersonById(long id);

    public LiveData<Person> getDistinctPersonById(long id) {
        return new DistinctLiveData<Person>(){
            @Override
            protected boolean equals(Person newObj, Person lastObj) {
                return newObj != null && !newObj.equals(lastObj);
            }

            @Override
            protected LiveData<Person> load() { return getPersonById(id); }
        }.asLiveData();
    }
}

@fatfatson
Copy link

Does it keep another copy of the result in memory? Is there an alternative if there are large data sets that need to be queried and we don't want to keep their copies?

+1

@gitrubs
Copy link

gitrubs commented Jul 10, 2019

Very nice solution

Here's a smaller kotlin version

fun <T> LiveData<T>.getDistinct(): LiveData<T> {
    val mediator = MediatorLiveData<T>()
    mediator.addSource(this, object: Observer<T> {
        private var initialized = false
        private var lastObj: T? = null

        override fun onChanged(t: T) {
            if (initialized && t == lastObj) return
            if (!initialized) initialized = true

            lastObj = t
            mediator.postValue(lastObj)
        }
    })
    return mediator
}

@gyallapu26
Copy link

gyallapu26 commented Aug 21, 2019

Any idea to avoid false positive notifications for observable queries in case of list !.

I want something like this

@query("SELECT * FROM Users WHERE username = :name")
protected abstract fun getUsersByNameFlowable(name String)
: Flowable<List>

fun getUsersByNameDistinctFlowable(id: String): Flowable<List<User>> =
        getUsersByNameFlowable(id) .distinctUntilChanged()

distinctUntilChanged considers subsequent items for comparison not for list i guess !.

Any solution to work around this issue ?

@akovalyev
Copy link

akovalyev commented Dec 8, 2019

Does it keep another copy of the result in memory? Is there an alternative if there are large data sets that need to be queried and we don't want to keep their copies?

+1

Instead of an object you can save its type and identifier and compare only mutable data.

@hArsh92
Copy link

hArsh92 commented Feb 4, 2020

You can use instead Transformations.distinctUntilChanged provided by androidx

So code will look like this

@Dao
abstract class UserDao {

    @Query("SELECT * FROM Users WHERE userid = :id")
    protected abstract fun getUserById(id: String): LiveData<User>

     fun getUserByIdDistinctLiveData(id: String): LiveData<User> = Transformations.distinctUntilChanged(getUserById(id))
}

Copy link

ghost commented Mar 26, 2020

You can use instead Transformations.distinctUntilChanged provided by androidx

So code will look like this

@Dao
abstract class UserDao {

    @Query("SELECT * FROM Users WHERE userid = :id")
    protected abstract fun getUserById(id: String): LiveData<User>

     fun getUserByIdDistinctLiveData(id: String): LiveData<User> = Transformations.distinctUntilChanged(getUserById(id))
}

+1

@selmanon
Copy link

selmanon commented Sep 1, 2020

same for Flowable distinctUntilChanged solved my issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment