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) {
myList.append(Boolean.TRUE);
} else {
myList.append(Boolean.FALSE);
}
}
// Filter out everything that isn't Boolean.TRUE
List<Boolean> trueList = new ArrayList<>();
for (Boolean nextBool : myList) {
if (nextBool) {
trueList.append(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 Collection
s.
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>() {
@Override
public Boolean call(Boolean b) {
return b.boolValue();
}
}).toList().toBlocking().first();
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();
}).toList().toBlocking().first();
Hopefully, this will help those of you out there who want to quickly filter a Collection
on Android. Happy hacking!
Subscribe to The Nothingness of Scott
Get the latest posts delivered right to your inbox