Skip to content

Instantly share code, notes, and snippets.

@SwiftyWang
Created April 16, 2018 04:50
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 SwiftyWang/460dbb6f27045b7b27d020032f558c9c to your computer and use it in GitHub Desktop.
Save SwiftyWang/460dbb6f27045b7b27d020032f558c9c to your computer and use it in GitHub Desktop.
Best Rx Fibonacci
import java.util.ArrayList;
import java.util.Arrays;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
public class Fibonacci {
public static Observable<Integer> fibonacci(int index) {
return Observable.range(1, 1).
repeat(index).
scan(new ArrayList<>(Arrays.asList(0, 1)), new BiFunction<ArrayList<Integer>, Integer, ArrayList<Integer>>() {
@Override
public ArrayList<Integer> apply(ArrayList<Integer> list, Integer integer) {
list.add(list.get(list.size() - 2) + list.get(list.size() - 1));
list.remove(0);
return list;
}
}
).map(new Function<ArrayList<Integer>, Integer>() {
@Override
public Integer apply(ArrayList<Integer> list) {
return list.get(list.size() - 1);
}
});
}
public static void main(String[] args) {
Observable<Integer> fibonacci = fibonacci(7);
Disposable disposable = fibonacci.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment