Combining the latter with the previous value in the observed stream

I am trying to figure out how to take the observed sequence Tand get both the last and previous value Tfrom my subscriber. Here is my spike code:

static void Main(string[] args)
{
    var latest = new Subject<string>();
    var previous = latest.SkipLast(1);
    var latestWithPrevious = latest.CombineLatest(previous, (l, p) => new { Latest = l, Previous = p });

    latestWithPrevious.Subscribe(x => Console.WriteLine("Latest: {0} Previous: {1}", x.Latest, x.Previous));

    latest.OnNext("1");
    latest.OnNext("2");
    latest.OnNext("3");

    Console.ReadKey();
}

I need the following output:

Publishing 1
Publishing 2
Latest: 2 Previous: 1
Publishing 3
Latest: 3 Previous: 2

However, I get the following:

Publishing 1
Publishing 2
Latest: 2 Previous: 1
Publishing 3
Latest: 3 Previous: 1
Latest: 3 Previous: 2

So, posting “3” on lateststarts two ticks in latestWithPrevious: the first has the old value for Previous, and the second has the correct value for Previous.

How can I achieve my goal here?

+4
source share
1 answer

Skip(1), SkipLast(1). SkipLast N .

, CombineLatest - , , , . Zip CombineLatest. Zip , .

, . latest - , , previous - , .

var source = new Subject<string>();
var previous = source;
var latest = source.Skip(1);
var latestWithPrevious = latest.Zip(previous, (l, p) => new { Latest = l, Previous = p});
+7

Source: https://habr.com/ru/post/1548640/


All Articles