I'm just playing with the concept of GroupBy inside Rx. So, I wondered how hard it would be to write a console application that continuously reads lines, groups them by similar words and just prints out the word among the current count of how often the word was written before. It really was a breeze to do that but I wonder if my attempt could be rewritten in a more elegant way. Especially if I can get rid of the nested Subscribes.
Here is what I have:
static void Main(string[] args)
{
var subject = new Subject<string>();
var my = subject.GroupBy(x => x);
my.Subscribe(x => x.Scan(new { Chars = string.Empty, Count = 0},
(a, chars) => new { Chars = chars, Count = a.Count + 1})
.Subscribe(result => Console.WriteLine("You typed {0} {1} times", result.Chars,
result.Count)));
while (true)
{
subject.OnNext(Console.ReadLine());
}
}
Result
test
you typed test 1 times
test
you typed test 2 times
hallo
you typed test 1 times
test
you typed test 3 times
...
Subscribewould make a bigger difference. – Richard Nov 12 '11 at 18:03