Skip to content

Reduce an empty observable #423

@zsxwing

Description

@zsxwing

Hi,

In RxJava, reduce(Func2<T, T, T> accumulator) may be not implemented correctly. Now reduce is implemented using scan. When reducing on empty observable, it will invoke onCompleted and do nothing. This is against my expectation. I suppose that reducing an empty observable should throw an exception.

Actually, Scan and Aggregate(I think this is reduce in C#) have different behaviors in C#. Scan an empty observable will do nothing, but Aggregate will throw a System.InvalidOperationException.

Here are my test codes in C#.
Scan:

Observable.Empty<int>().Scan((x, y) => x + y).Subscribe(
                x => 
                    Console.WriteLine("subscriber got " + x)
            );

Aggregate:

Observable.Empty<int>().Aggregate((x, y) => x + y).Subscribe(
                x => 
                    Console.WriteLine("subscriber got " + x)
            );

I also tried the reduce method in other languages.

List[Int]().reduce(_ + _) will throw
java.lang.UnsupportedOperationException: empty.reduceLeft in scala.

reduce(lambda x, y: x + y, []) will throw reduce() of empty sequence with no initial value in python.

If reducing an empty observable throws an exception, we can implement min and max by reduce directly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions