Streams
Learn about data streams in Java and RxJava and why we prefer RxJava streams.
Java’s streams
If we think about it, a stream is not a new concept. A Collection
in Java can be modeled as a stream where each element in the Collection
is an item emitted in the stream.
On Android, click events can be a stream, location updates can be a stream, push notifications can be a stream, and so on.
Imperative vs. declarative approach
Traditionally, processing data streams in Java is done imperatively. For example, given a list of User
objects, say we want to return only those that have a blog. That function might look something like this:
/*** Returns all users with a blog.* @param users the users* @return users that have a blog*/public static List<User> getUsersWithABlog(List<User> users) {List<User> filteredUsers = new ArrayList<>();for (User user : users) {if (user.hasBlog()) {filteredUsers.add(user);}}return filteredUsers;}
The above code might look very familiar: a loop that iterates through each item in the provided collection, an if-statement to check if a condition is true, and for those that pass, the necessary action is performed, meaning that the item is added ...