Question

I have the program with the following code as a simplified version of something else that I am trying to do:

Subject<int> numbers = new Subject<int>();
Subject<string> strings = new Subject<string>();
var oddsAndEvens = numbers.GroupBy(i => i % 2);

var zipped = oddsAndEvens.Zip(strings, 
    (group, str) => group.Select(
        i => new Tuple<int, string>(i, str)))
        .SelectMany(x => x);
zipped.Subscribe(t => Console.WriteLine("{0}, {1}", t.Item1, t.Item2));

numbers.OnNext(0);
strings.OnNext("even");
numbers.OnNext(2);

strings.OnNext("odd");
numbers.OnNext(1);
numbers.OnNext(3);

Console.ReadKey();

The output from the program is

2, even
1, odd
3, odd

Whereas I would expect the output to be

0, even
2, even
1, odd
3, odd 

I think that what is happening is that the 0 is being observed and a group is created. Each group cannot output any values until a string is observed (and the two are zipped together), but by the time that the first string is observed the number 0 has already been and gone. If I understand RX correctly the group should not output the number 0 until there is something subscribed to it.

Have I misunderstood something? Is there a way to stop the group from outputting until there is a string observed?

Was it helpful?

Solution

It's not clear what you are trying to achieve here. The Rx is behaving as it should.

The Zip operator's result selector is capturing a group stream and a string. Note it is not capturing the events of the group stream.

When the result selector runs, the group stream has already sent 0. The SelectMany will subscribe to the group stream after the 0 event has gone.

It's only when the string is the first event sent (put the OnNext("even") up a line) that you'll be OK because the group will be subscribed to when it is created, which is just before the first event is sent into the group.

The GroupBy operator will not remember and replay historic events, and it's source is hot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top