Created
April 16, 2018 04:50
-
-
Save SwiftyWang/460dbb6f27045b7b27d020032f558c9c to your computer and use it in GitHub Desktop.
Best Rx Fibonacci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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