Created
November 9, 2012 17:25
-
-
Save jminadeo/4046981 to your computer and use it in GitHub Desktop.
Observable example from MS for linqpad
This file contains hidden or 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
void Main() | |
{ | |
IObservable<Ticket> ticketObservable = Observable.Create((Func<IObserver<Ticket>, IDisposable>)TicketFactory.TicketSubscribe); | |
using(IDisposable handle = ticketObservable.Subscribe(ticket => Console.WriteLine(ticket.ToString()))) | |
{ | |
Console.WriteLine("\nPress ENTER to unsubscribe...\n"); | |
Console.ReadLine(); | |
} | |
} | |
class Ticket | |
{ | |
private readonly string ticketID; | |
private readonly DateTime timeStamp; | |
public Ticket(string tid) | |
{ | |
ticketID = tid; | |
timeStamp = DateTime.Now; | |
} | |
public override string ToString() | |
{ | |
return String.Format("Ticket ID : {0}\nTimestamp : {1}\n", ticketID, timeStamp.ToString()); | |
} | |
} | |
public class TicketFactory : IDisposable | |
{ | |
private bool bGenerate = true; | |
internal TicketFactory(object ticketObserver) | |
{ | |
Task.Factory.StartNew(new Action<object>(TicketGenerator), ticketObserver); | |
} | |
public void Dispose() | |
{ | |
bGenerate = false; | |
} | |
private void TicketGenerator(object observer) | |
{ | |
IObserver<Ticket> ticketObserver = (IObserver<Ticket>)observer; | |
Ticket t; | |
while (bGenerate) | |
{ | |
t = new Ticket(Guid.NewGuid().ToString()); | |
ticketObserver.OnNext(t); | |
Thread.Sleep(250); | |
} | |
} | |
public static IDisposable TicketSubscribe(object ticketObserver) | |
{ | |
return new TicketFactory(ticketObserver); | |
} | |
} |
You will also need to use the Linqpad Nuget integration to grab the Reactive Extensions and add the following usings (there are more here then you actually need but since I am still sorting out what is required and when, this gets it all in there):
System
System.Reactive
System.Reactive.Concurrency
System.Reactive.Disposables
System.Reactive.Joins
System.Reactive.Linq
System.Reactive.PlatformServices
System.Reactive.Subjects
System.Reactive.Threading.Tasks
System.Threading.Tasks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Originally from: http://msdn.microsoft.com/en-us/library/hh229114(v=vs.103).aspx