Sunday, March 1, 2015

Java 8 Stream to Rx-Java Observable

I was recently looking at a way to convert a Java 8 Stream to Rx-Java Observable.

There is one api in Observable that appears to do this :

public static final <T> Observable<T> from(java.lang.Iterable<? extends T> iterable)

So now the question is how do we transform a Stream to an Iterable. Stream does not implement the Iterable interface, and there are good reasons for this. So to return an Iterable from a Stream, you can do the following:

Iterable iterable = new Iterable() {
    @Override
    public Iterator iterator() {
        return aStream.iterator();
    }
};

Observable.from(iterable);

Since Iterable is a Java 8 functional interface, this can be simplified to the following using Java 8 Lambda expressions!:

Observable.from(aStream::iterator);

First look it does appear cryptic, however if it is seen as a way to simplify the expanded form of Iterable then it slowly starts to make sense.

Reference:
This is entirely based on what I read on this Stackoverflow question.

1 comment:

  1. ...and to go back the other way - I worked this out: (RxJava Observable-to-java.util.Stream)

    http://www.cogmission.ai/2016/04/06/speed-blog-how-to-convert-an-rx-observable-to-a-java-util-stream/

    ReplyDelete