假设:
class CharPair
{
char _a;
char _b;
CharPair(char a, char b) { _a = a; _b = b; }
}
IObservable<char> keyPresses = ... // a sequence of key presses
如何创建新的 IObservable&lt; CharPair&gt; ?
?E.g。
'a','1','b','2','c','3','d','4'
->
CharPair('a','1'),CharPair('b','2'),CharPair('c','3'),CharPair('d','4')
到目前为止,我有以下内容,但这似乎相当漫长,可以改进吗?
IObservable<char> keyPresses = KeyPresses().ToObservable().Publish();
var odds = keyPresses.Where((_,i) => (i&1) == 1);
var evens = keyPresses.Where((_,i) => (i&1) == 0);
IObservable<CharPair> charPairs = evens.Zip(odds, (e, o) => new CharPair(e,o));
答案 0 :(得分:2)
BufferWithCount 应该有帮助,您可以这样做:
var keyPressed = Observable.Create<ConsoleKey>(
o =>
{
while (true)
{
var consoleKeyInfo = Console.ReadKey(true);
o.OnNext(consoleKeyInfo.Key);
}
}
);
var paired = keyPressed
.BufferWithCount(2)
.Select(x => new {a = x[0], b = x[1]});
paired.Subscribe(Console.WriteLine);