Skip to content

Scan Operator, with and without initial value behave wildly different. Intended? #286

Closed
@ultimateshipii

Description

@ultimateshipii

I'm quite new to this RX stuff so forgive me if there something simple I'm missing here.

I was trying to use scan and found that it did not behave as I expected. This code illustrates how:

public class ScanIssue
{
    public static void main(String[] args) throws InterruptedException
    {
        PublishSubject<Integer> source  = PublishSubject.create();

        Func2<Integer, Integer, Integer> accumulator = new Func2<Integer, Integer, Integer>()
        {
            @Override
            public Integer call(Integer a, Integer b)
            {
                return a + b;
            }
        };

        Observable<Integer> scan = Observable.scan(source, accumulator);
//        Observable<Integer> scan = Observable.scan(source, 0, accumulator);


        print("A", scan);
        print("B", scan);
        print("C", scan);
//        print("D", scan);
//        print("E", scan);

        Thread.sleep(1000);
        source.onNext(1);
        Thread.sleep(1000);
        source.onNext(1);
    }

    private static <T> void print(final String prefix, Observable<T> source)
    {
        source.subscribe(new Action1<T>()
        {
            @Override
            public void call(T s)
            {
                System.out.println(prefix + ": " + s);
            }
        });
    }
}

I would expect it to output nothing on the first onNext and this on the second:

A: 2
B: 2
C: 2

Where I don't care about the order of A,B & C.

But instead it outputs this on the first one:

B: 1
B: 2
B: 3

and this on the second:

B: 4
B: 5
B: 6

B can be any of A, B and C but always the same all 6 times.

  • If I switch to the one with initial value it works as I expect
  • The more subscriptions I add the worse it gets
  • The type of source does not seem to matter (tried with a hand rolled one)

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