Created
July 7, 2011 11:20
-
-
Save hodzanassredin/1069319 to your computer and use it in GitHub Desktop.
Using RX for object level CQRS, method proxy and logging.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Reactive.Subjects; | |
using System.Reactive.Linq; | |
namespace FpCs | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var test = new Proto(); | |
test.SetI.Subscribe(i => Console.WriteLine("New I = " + i)); | |
var sSubscr = test.SetS.Subscribe(s => Console.WriteLine("New S = " + s)); | |
test.SetI.Select(i => test) | |
.Merge(test.SetS.Select(i => test)).Select((proto, index) => new { P = proto, I = index + 1 }) | |
.Subscribe(s => Console.WriteLine("Proto after change " + s.P + " this is " + s.I + " change")); | |
test.SetI.OnNext(1); | |
test.SetS.OnNext("s"); | |
sSubscr.Dispose(); | |
test.SetS.OnNext("new s"); | |
Action<int, ISubject<int>> proxy = (i, old) => old.OnNext(i + 1); | |
proxy.AddAsBeforeProxyTo(ref test.SetI); | |
test.SetI.OnNext(5); | |
Console.ReadKey(); | |
} | |
} | |
public class Proto | |
{ | |
public Proto() | |
{ | |
var i = 0;// like a fields | |
var s = ""; | |
SetI = new Subject<int>(); | |
SetI.Subscribe(ni => i = ni); | |
SetS = new Subject<String>(); | |
SetS.Subscribe(ns => s = ns); | |
GetI = () => i; | |
GetS = () => s; | |
} | |
public ISubject<int> SetI; //like a properties | |
public Func<int> GetI; | |
public ISubject<string> SetS; | |
public Func<string> GetS; | |
public override string ToString() | |
{ | |
return String.Format("{{s={0} i={1}}}", GetS(), GetI()); | |
} | |
} | |
public static class SubjectHelper | |
{ | |
//Need to rtfm to know how to do it correctly | |
public static void AddAsBeforeProxyTo<T>(this Action<T, ISubject<T>> proxy, ref ISubject<T> acc) | |
{ | |
var p = new Subject<T>(); | |
var old = acc; | |
p.Subscribe(x => proxy(x, old)); | |
acc = p; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
New I = 1
Proto after change {s= i=1} this is 1 change
New S = s
Proto after change {s=s i=1} this is 2 change
Proto after change {s=new s i=1} this is 3 change
New I = 6
Proto after change {s=new s i=6} this is 4 change