Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
}
@anotherdev

This comment has been minimized.

Copy link

commented Feb 22, 2018

For distinct LiveData<T>, is it ok to use this approach?

LiveData<User> getUserByIdDistinctLiveData(String id) {
        return LiveDataReactiveStreams.fromPublisher(
                getUserByIdDistinctFlowable(id)
                        .distinctUntilChanged());
}
@gabin8

This comment has been minimized.

Copy link

commented Mar 20, 2018

how it looks like in Java?

@or-dvir

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Jan 24, 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.