I'm trying to find the smaller number in a sequence using RxJava. This is my first attemp to solve the task. It works (I got 1 as a result) but because I'm still a newbie in RxJava I'm hundred percent sure there is a better solution:
Observable<List<Integer>> sequence = Observable.create(new Observable.OnSubscribe<List<Integer>>() {
@Override
public void call(Subscriber<? super List<Integer>> subscriber) {
subscriber.onNext(Arrays.asList(new Integer[]{10, 9, 8, null, 1, 2, 3, 4}));
subscriber.onCompleted();
}
});
final int[] minValue = {Integer.MAX_VALUE};
sequence.flatMap(numList -> Observable.from(numList))
.filter(number -> number != null)
.filter(number -> {
if (number < minValue[0]) {
minValue[0] = number;
return true;
} else {
return false;
}
})
.last()
.subscribe(number -> {
Log.i("App", "The smaller value in the sequence is " + number);
});
Any suggestion about how to do it properly? :)
Using the the rxjava-math module the min() operator will do what you want.
sequence
.flatMap(numList -> Observable.from(numList)
.filter(number -> number != null)
.min()
.subscribe(number -> {
Log.i("App", "The smaller value in the sequence is " + number);
});
You can also roll your own version of min() using reduce()
sequence
.flatMap(numList -> Observable.from(numList)
.filter(number -> number != null)
.reduce(Integer.MAX_VALUE,
(currentMin, number) -> number < currentMin ? number : currentMin)
.filter(number -> number != Integer.MAX_VALUE)
.subscribe(number -> {
Log.i("App", "The smaller value in the sequence is " + number);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With