Skip to content

Instantly share code, notes, and snippets.

@ytRino
Last active August 29, 2015 14:14
Show Gist options
  • Save ytRino/1517f3ea21941683d33d to your computer and use it in GitHub Desktop.
Save ytRino/1517f3ea21941683d33d to your computer and use it in GitHub Desktop.
RxFibonacci
// in android :p
private void printFib(int l) {
fib(l).subscribe(new Action1<List<Long>>() {
@Override
public void call(List<Long> fib) {
Log.v(TAG, fib.toString());
}
});
}
private Observable<List<Long>> fib(int l) {
// f(n-2)
final BehaviorSubject<Long> s2 = BehaviorSubject.create();
// f(n-1)
final BehaviorSubject<Long> s1 = BehaviorSubject.create();
final Observable<Long> f2 = s2.startWith(0L, 1L).doOnNext(new Action1<Long>() {
@Override
public void call(Long t) {
Log.v("f(n-2)", t.toString());
}
});
final Observable<Long> f1 = s1.startWith(0L, 0L).doOnNext(new Action1<Long>() {
@Override
public void call(Long t) {
Log.v("f(n-1)", t.toString());
s2.onNext(t);
}
});
return Observable.zip(f1, f2, new Func2<Long, Long, Long>() {
@Override
public Long call(Long n1, Long n2) {
return n1 + n2;
}
}).doOnNext(new Action1<Long>() {
@Override
public void call(Long t) {
s1.onNext(t);
}
}).take(l).toList();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment