Quick Filtration with RxAndroid

If you're not using RxAndroid, you should consider adding it as a dependency to your Android project. It makes life significantly easier when working with REST API calls.

However, once you've added it, there are a bunch of other benefits besides just simplifying REST calls. Consider the following code snippet:

// Set up our list of items
List<Boolean> myList = new ArrayList<>();  
for (int i = 0; i < 200; i++) {  
  if (i % 2 == 0 || i % 3 == 0) {
  } else {

// Filter out everything that isn't Boolean.TRUE
List<Boolean> trueList = new ArrayList<>();  
for (Boolean nextBool : myList) {  
  if (nextBool) {

myList = trueList;  

That seems like a lot of code just to perform a simple filter() method, right? The thing is, Java 7 (and Android right now) doesn't really provide a good method of filtering Collections.

However, if you're using RxAndroid, there's an easy way to do this same filtering:

myList = Observable.from(myList).filter(new Func1<Boolean, Boolean>() {  
      public Boolean call(Boolean b) {
        return b.boolValue();

As an added bonus, if you include the Retrolambda dependency in your code, you can simplify this even further to:

myList = Observable.from(myList).filter(b -> {  
  return b.boolValue();

Hopefully, this will help those of you out there who want to quickly filter a Collection on Android. Happy hacking!

comments powered by Disqus