Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava: How to find the smaller number in a sequence

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? :)

like image 467
Diego Palomar Avatar asked Dec 20 '22 02:12

Diego Palomar


1 Answers

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);
    });
like image 100
kjones Avatar answered Jan 28 '23 21:01

kjones