How to filter duplicate values emitted by observable in RXJava?

ぃ、小莉子 提交于 2020-01-31 22:09:11

问题


I have a collection of objects, where i want to suppress duplicate items. I know about Distinct operator, but if i am not mistaken it compare items by properly overrided hashcode method. But what if my hashcode returns different values for same objects, and i want to set equality by my own. distinct have 2 overloaded methods - one without params and one with Func1 param,i suppose that i should use 2nd method, but how exaclty?

    .distinct(new Func1<ActivityManager.RunningServiceInfo, Object>() {
                        @Override
                        public Object call(ActivityManager.RunningServiceInfo runningServiceInfo) {
                            return null;
                        }
                    })

回答1:


Yep you are right that you need to have consistent equals() and hashcode() methods on your object to be able to use distinct() because under the covers the distinct operator uses a HashSet.

The version of distinct with a Func1 allows you to convert the object into something that you want to be distinct (but must implement consistent equals and hashcode methods).

Suppose I have an Observable<Person> where Person is like this:

class Person {
    String firstName;
    String lastName;
}

Then to count the number of distinct first names I could do this:

persons.distinct(person -> person.firstName).count();



回答2:


Not sure if simplest way but you can do it with reduce. Reduce takes a collection and an action. Within the action you are responsible for adding the elements to the collection yourself. There you can do whatever logic you'd like and conditionally add elements to the collection.



来源:https://stackoverflow.com/questions/32286371/how-to-filter-duplicate-values-emitted-by-observable-in-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!