The ‘distinct’ness of RxJava

manideep lanka
Aug 24, 2017 · 2 min read

RxJava provides an intuitive way to abstract common operations. We’ll see a few imaginary scenarios from the Harry Potter world to show how we can suppress duplicate emissions from an Observable using distinct() and distinctUntilChanged().

So Professor McGonagall, along with the heads of other houses want to pick a single student from each of their houses to honor them with a special task.

Students arrive in this manner:

the students stream

Harry, Ron, Dean and Hermione are from Gryffindor, Draco is from Slytherin, Cho and Luna are from Ravenclaw and Cedric is from Hufflepuff.

To select their students, the heads decide to use distinct() :

see the lambda provided to distinct()

Now, the lucky students are:

What has made them the chosen ones? distinct! Actually, it is the lambda we provided to distinct(). A student will be ignored if a student was already selected from the same house!

Later, the heads realized they needed to pick students such that no two of them from the same house are next to each other. Snape suggested distinctUntilChanged(). Wicked!

again, see the lambda

The lucky ones this time:

Poor Luna and Dean didn’t make it this time too, as they arrived just after their house mates and not after someone from a different house :(

Notice the heads passed a lambda to both distinct() and distinctUntilChanged(), with the house as the key that differentiates the students. If they didn’t do it, its the default equality that comes into play for distinguishing the students. Perhaps…the make of their wands?

)

manideep lanka

Written by

Software engineer, AI enthusiast

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade