Here is such a simple task that does not want to be solved.

looks like this

Observable<Integer> result = sum(Observable.just(1, 3, 4, 6, 3)); @NonNull public static Observable<Integer> sum(@NonNull Observable<Integer> observable) { return Observable.just(0); } 

I tried to write sumInteger() but does not recognize this method.

How do you need to write a method so that it returns the sum of all numbers?

    1 answer 1

    sumInteger() is a method of the MathObservable class included in rxjava-math . If this library is in dependencies, you can do this:

     Observable<Integer> numbers = Observable.just(1, 3, 4, 6, 3); Integer result = MathObservable.sumInteger(numbers) .toBlocking() .firstOrDefault(0); 

    And you can without it:

     Integer result = numbers.reduce(0, new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer a, Integer b) { return a + b; } }) .toBlocking() .firstOrDefault(0); 

    Or easier, if the code is only for Android 7, where lambdas are supported:

     Integer result = numbers.reduce(0, Integer::sum) .toBlocking() .firstOrDefault(0); 
    • "if the code is only for Android 7, where lambdas are supported" - uh ... in java, does lambda support happen at runtime, and not at compilation? - Qwertiy ♦
    • @Qwertiy Android Studio will generate an error "Lambda expressions are not supported at this language level" if the API Level is below the 24th. And the documentation says that Java 8 features are supported only with Android 7. - Sergey Gornostaev
    • one
      and there is also github.com/orfjackal/retrolambda - rjhdby