我有一个IObservable<byte[]>
,它在字节数组中给了我一个不确定数量的字节。我想知道如何从那个,返回一个IObservable<byte[]>
,每个字节数组中都有一定数量的字节。让我们假设每次需要10个字节。
也就是说,如果我订阅,得到以下输入:
{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));
输出将是
3
2
3
1
5
1
2
2
我想把上面的输入转换成这样:
{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));
输出将是
10
10
如果传入的字节量大于单个输出数据包,也必须工作,即:
{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}
应该变成
{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},等待更多的输入)
这很简单。试试这个:
Bytes
.SelectMany(b => b)
.Buffer(10)
.Select(bs => bs.ToArray());
经过一番思考和修修补补,我想出了一个解决方案。下面的代码完成了我想要的:
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 ) );
这可能是低效的,我几乎可以肯定这不是最有效的方法,所以如果有人能想出一个更好的,更有效的解决方案,我洗耳恭听!