public
Description: My lame attempt at mimicking the Rx framework
Homepage:
Clone URL: git://github.com/paulbatum/Reactive.git
Reactive / Form1.cs
100644 71 lines (58 sloc) 2.165 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Linq.Expressions;
 
namespace Reactive
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            //Func<MouseEventArgs, int> slowOperation = args =>
            //{
            // System.Threading.Thread.Sleep(3000);
            // if(args.Button == MouseButtons.Middle)
            // throw new Exception("MIDDLE BUTTON NOT ALLOWED!!!");
            // return args.X;
            //};
 
            //IObservable<string> messages = from md in button1.GetMouseDowns()
            // from x in slowOperation.AsAsyncObservable(md)
            // where md.Button == MouseButtons.Right
            // select "Mouse down: " + x + "\n";
 
            IObservable<MouseEventArgs> mouseEvents = button1.GetMouseDowns();
 
            IObservable<string> messages = from md in mouseEvents
                                           select "Mouse down at: " + md.X + "\n";
 
            messages.Subscribe(new TextBoxUpdater(textBox1));
        }
 
        public class TextBoxUpdater : IObserver<string>
        {
            private readonly TextBox _textBox;
 
            public TextBoxUpdater(TextBox textBox)
            {
                _textBox = textBox;
            }
 
            private void AppendText(string text)
            {
                Action textboxUpdater = () => _textBox.AppendText(text);
                _textBox.BeginInvoke(textboxUpdater);
            }
 
            public void OnNext(string s)
            {
                AppendText(s);
            }
 
            public void OnDone()
            {
                AppendText("Done\n");
            }
 
            public void OnError(Exception e)
            {
                AppendText("Error: " + e.Message);
            }
        }
 
    }
}