Benjamin
Benjamin

Reputation: 900

Rx Dynamically Sized Sliding Buffer

I'm not entirely sure how to phrase this, so I'm sorry if I got it wrong. I have a sequence of events we'll say look like this:

0,1,2,3,4,5,6,7,8,9,...

I want to provide my program with an IObservable that returns buffers that look like this:

[0],[0,1],[0,1,2],[0,1,2,3],[1,2,3,4],[2,3,4,5],[3,4,5,6],....

Or some other maximum buffer size that's not 4. If I could feed in the buffer arguments like you can with timed buffer calls, it would be easy, but there isn't an overload for that, so I tried constructing the sequence manually:

target.LogEvents.Buffer(1,1).Take(1).Concat(target.LogEvents.Buffer(2,1).Take(1)).Concat(target.LogEvents.Buffer(3,1).Take(1)).Concat(target.LogEvents.Buffer(4, 1)).Subscribe(...);

But that didn't work. It gave me

[0],[1,2],[3,4,5],[6,7,8,9],[7,8,9,10],....

How do I generate my sequence?

Upvotes: 0

Views: 278

Answers (1)

Enigmativity
Enigmativity

Reputation: 117037

Does this work for you?

IObservable<IEnumerable<int>> query = 
    source
        .Scan(Enumerable.Empty<int>(), (a, x) =>
            a.Concat(new [] { x }).TakeLast(4).ToList());

You need to NuGet both "Rx-Main" and "Ix-Main" for this to work.

Upvotes: 2

Related Questions