Alex
Alex

Reputation: 3470

Convert IObservable<byte[]> with irregular length byte arrays to IObservable<byte[]> with regular length arrays

I have an IObservable<byte[]> that gives me an uncertain amount of bytes in the byte array. I want to know how I go from that, to returning an IObservable<byte[]> with a set amount of bytes in each byte array. Let's assume we want 10 bytes at a time.

That is to say, if I get the following input if I were to subscribe:

{1, 2, 3, 4}
{5, 6}
{7, 8, 9}
{10}
{11, 12, 13, 14, 15}
{16}
{17, 18}
{19, 20}

Bytes.Subscribe(b => Console.WriteLine(b.Length));

The output would be

3
2
3
1
5
1
2
2

What I would like is to convert the input above into this:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

Bytes.<WhateverItTakesToDoThat>.Subscribe(b => Console.WriteLine(b.Length));

The output would be

10
10

It must also work if an amount of bytes come in that are larger than a single output packet, i.e.:

{21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}
{33, 34, 35, 36, 37, 38, 39, 40, 41}
{42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52}

Should be turned into

{21, 22, 23, 24, 25, 26, 27, 28, 29, 30}
{31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
{41, 42, 43, 44, 45, 46, 47, 48, 49, 50}

(and be holding on to {51, 52}, waiting for more input to come along)

Upvotes: 1

Views: 206

Answers (2)

Alex
Alex

Reputation: 3470

I came up with one solution after a bit of thinking and tinkering. The following code does what I want:

Bytes.Select( b => b.ToObservable() ) // Convert input to IObservable<IObservable<byte>>
.Merge( 1 ) // Merges the IObservable<IObservable<byte>> to an IObservable<byte>
            // with the bytes in the right order
.Buffer( 4 ) // Wait until we have 4 bytes ready
.Select( bl => bl.ToArray() ) // Take these 4 bytes and turn them back into an array
.Subscribe( b => Console.WriteLine( b.Length ) );

This is probably inefficient, and I'm almost certain it's not he most efficient way of doing this, so if somebody out there can come up with a better, more efficient solution, I'm all ears!

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117027

It's easy. Try this:

    Bytes
        .SelectMany(b => b)
        .Buffer(10)
        .Select(bs => bs.ToArray());

Upvotes: 4

Related Questions