Skip to content

Instantly share code, notes, and snippets.

@colintheshots
Last active December 3, 2016 15:45
Show Gist options
  • Save colintheshots/f09659edb4c2e64d803a to your computer and use it in GitHub Desktop.
Save colintheshots/f09659edb4c2e64d803a to your computer and use it in GitHub Desktop.
package com.octo.android.robospice.sample.retrofit;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
/**
* Created by colintheshots on 6/16/14.
*/
public class RxFibonacci {
public static void main(String[] args) {
rxFibN(20).subscribe(new Action1<Integer>() {
@Override
public void call(Integer result) {
System.out.println(result);
}
});
}
static Observable<Integer> rxFibN(final int n) {
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
int [] n1 = {0,1};
for (int i = 1; i<n; i++) {
n1 = new int[]{n1[1], n1[1] + n1[0]};
subscriber.onNext(n1[1]);
}
subscriber.onCompleted();
}
}).last();
}
}
@wleroux
Copy link

wleroux commented Dec 3, 2016

Hey Colin,

I tried implementing fib sequence for kicks on RxJava2, here's what I came up with:

package test;

import io.reactivex.Observable;

import java.math.BigInteger;

/**
 * The main entry point.
 */
public class Main {
  public static void main(String[] args) {
    Observable<BigInteger> fibSequence = Observable.create(subscriber -> {
      BigInteger a = BigInteger.ZERO;
      BigInteger b = BigInteger.ONE;
      while (!subscriber.isDisposed()) {
        BigInteger nextNumber = a.add(b);
        a = b;
        b = nextNumber;

        subscriber.onNext(a);
      }
      subscriber.onComplete();
    });

    fibSequence
        .skip(1)
        .take(10)
        .subscribe(System.out::println);
  }
}

This allows me to request the number of fib sequences as desired without having to create a new stream. Thought I'd post it here as I've found this when looking for an example (I was trying to find how to request n items idiomatically.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment