Skip to content

Instantly share code, notes, and snippets.

@mikea
Created May 14, 2014 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikea/4dfd8153a1b53d06ec57 to your computer and use it in GitHub Desktop.
Save mikea/4dfd8153a1b53d06ec57 to your computer and use it in GitHub Desktop.
Attempt to implement headAndTail function. Using publish().refCount() to avoid double reading a file. Doesn't work at all.
public class HeadTest {
public static void main(String[] args) {
Observable<Integer> fileReader = Observable.create((Observable.OnSubscribe<Integer>) subscriber -> {
System.out.println("Reading from a file");
subscriber.onNext(100); // header
for (int i = 0; i < 10; ++i) {
subscriber.onNext(i);
}
subscriber.onCompleted();
});
Pair<Observable<Integer>, Observable<Integer>> headAndTail = headAndTail(fileReader);
Integer headerValue = BlockingObservable.from(headAndTail.x).single();
Observable<Integer> processedValues = headAndTail.y.map(i -> i + headerValue);
BlockingObservable.from(processedValues).forEach(System.out::println);
}
public static <T> Pair<Observable<T>, Observable<T>> headAndTail(Observable<T> o) {
Observable<T> published = o.publish().refCount();
return new Pair<>(published.first(), published.skip(1));
}
public static class Pair<X, Y> {
public final X x;
public final Y y;
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
}
}
Reading from a file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment