Reactive Extensions: Matching Values ​​with IObservable

Given:

 class CharPair 
 {
     char _a;
     char _b;
     CharPair(char a, char b) { _a = a; _b = b; }
 }

 IObservable<char> keyPresses = ... // a sequence of key presses

How can I take all two characters and create a new IObservable <CharPair>?

eg.

 'a','1','b','2','c','3','d','4'
    -> 
 CharPair('a','1'),CharPair('b','2'),CharPair('c','3'),CharPair('d','4')

So far I have the following, but it seems rather long, can it be improved?

 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));
+3
source share
1 answer

BufferWithCount should help, you can do something like this:

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);
+2
source

Source: https://habr.com/ru/post/1788236/


All Articles