Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter duplicate values emitted by observable in RXJava?

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;
                        }
                    })
like image 299
Lester Avatar asked Aug 29 '15 13:08

Lester


People also ask

How to filter observables in RxJava?

For this purpose, RxJava offers various filtering capabilities. Let's start looking at the filter method. 2.1. The filter Operator Simply put, the filter operator filters an Observable making sure that emitted items match specified condition, which comes in the form of a Predicate. Let's see how we can filter only the odd values from those emitted:

What is RxJava’s observable emits an item from an observable?

This article is part of RxJava Introduction series. You can checkout the entire series here: This operator only emits an item from an Observable if a particular timespan has passed without it emitting another item.

How to pass a list of duplicate values to an observable?

When we pass a list of duplicate integer values, the Observable uses the distinct () operator to emit only unique values from the list. This operator emits only one item ’ n’ emitted by an Observable. We can specify the position we need to emit using the elementAt operator. For instance, elementAt (0) will emit the first item in the list.

What is the use of following operator in observable in Java?

Following are the operators which are used to selectively emit item (s) from an Observable. Emits items only when timeout occurs without emiting another item. Emits only unique items. emit only item at n index emitted by an Observable.


1 Answers

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();
like image 132
Dave Moten Avatar answered Sep 23 '22 09:09

Dave Moten