Get previous element in IObservable without re-evaluating the sequence

Posted by dcstraw on Stack Overflow See other posts from Stack Overflow or by dcstraw
Published on 2010-05-12T16:15:09Z Indexed on 2010/05/12 16:24 UTC
Read the original article Hit count: 175

Filed under:
|
|

In an IObservable sequence (in Reactive Extensions for .NET), I'd like to get the value of the previous and current elements so that I can compare them. I found an example online similar to below which accomplishes the task:

sequence.Zip(sequence.Skip(1), (prev, cur) => new { Previous = prev, Current = cur })

It works fine except that it evaluates the sequence twice, which I would like to avoid. You can see that it is being evaluated twice with this code:

var debugSequence = sequence.Do(item => Debug.WriteLine("Retrieved an element from sequence"));
debugSequence.Zip(debugSequence.Skip(1), (prev, cur) => new { Previous = prev, Current = cur }).Subscribe();

The output shows twice as many of the debug lines as there are elements in the sequence.

I understand why this happens, but so far I haven't found an alternative that doesn't evaluate the sequence twice. How can I combine the previous and current with only one sequence evaluation?

© Stack Overflow or respective owner

Related posts about system.reactive

Related posts about iobservable