SlideShare a Scribd company logo
1 of 58
Download to read offline
Rx:	
  Curing	
  your	
  Asynchronous	
  
Programming	
  Blues	
  
Bart	
  J.F.	
  De	
  Smet	
  
Microso'	
  Corpora,on	
  
bartde@microso'.com	
  
Why	
  Should	
  I	
  Care?	
  
                                                                                  GPS	
  


                                         RSS	
  	
  	
  	
  	
  	
  feeds	
  

Stock	
  
            ,ckers
                     	
  




            Social	
  
            media	
  




                                                                                Server	
  management	
  
Mission	
  Statement	
  
Too	
  hard	
  today!	
                     (!  ◦  ")(#)  =  !("(#))



 Rx is a library for composing
asynchronous and event-based
  programs using observable
           sequences.
                                                   Queries?	
  LINQ?	
  

                                              •    .NET	
  3.5	
  SP1	
  and	
  4.0	
  
                                              •    Silverlight	
  3	
  and	
  4	
  
                                              •    XNA	
  3.1	
  for	
  XBOX	
  and	
  Zune	
  
                                              •    Windows	
  Phone	
  7	
  
                                              •    JavaScript	
  (RxJS)	
  

                       MSDN	
  Data	
  Developer	
  Center	
                    NuGet	
  
Essen,al	
  Interfaces	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
                                            C# 4.0 covariance

interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
                                                                       You could get
	
  	
  	
  	
  bool	
  	
  	
  MoveNext();	
  
                                                                          stuck
	
  	
  	
  	
  T	
  	
  	
  	
  	
  	
  Current	
  {	
  get;	
  }	
  
	
  	
  	
  	
  void	
  	
  	
  Reset();	
  
}	
  
Essen,al	
  Interfaces	
  

       (WaiHng	
  to	
  move	
  next)	
  




                               C# 4.0 covariance
                            moving	
  on	
  




                                               You could get
                                                  stuck
Mathema,cal	
  Duality	
  
Because	
  the	
  Dutch	
  are	
  (said	
  to	
  be)	
  cheap	
  

 –  Electricity:	
  	
  inductor	
  and	
  capacitor	
  




 –  Logic:	
  	
  De	
  Morgan’s	
  Law	
  
     ¬(%∧&)≡¬%∨¬&	
                           ¬(%∨&)≡¬%∧¬&	
  



 –  Programming?	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  
     The	
  recipe	
  to	
  dualiza,on	
  
                              h^p://en.wikipedia.org/wiki/Dual_(category_theory)




                                    Reversing arrows…
                              Input becomes output and vice
                                          versa
Making	
  a	
  U-­‐turn	
  
 in	
  synchrony	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  bool	
  	
  MoveNext();	
  
	
  	
  T	
  	
  	
  	
  	
  Current	
  {	
  get;	
  }	
  
                                                            Properties
	
  	
  void	
  	
  Reset();	
                             are methods
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  bool	
  	
  MoveNext();	
  
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
  
	
  	
  void	
  	
  Reset();	
  
                                          A historical mishap
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  bool	
  	
  MoveNext();	
                 No checked
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
   exceptions in .NET /
                                                       C#
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  bool	
  	
  MoveNext()	
  throws	
  Exception;	
  
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
  
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  bool	
  	
  MoveNext()	
  throws	
  Exception;	
  
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
  
                                                   This is an
}	
  
                                              output too!
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  (bool	
  |	
  Exception)	
  MoveNext();	
  
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
  
                                               Discriminated	
  union	
  
}	
                  Really only two                type	
  (“or”)	
  
             values
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  (true	
  |	
  false	
  |	
  Exception)	
  MoveNext();	
  
	
  	
  T	
  	
  	
  	
  	
  GetCurrent();	
  
}	
                                                     Got true?
                                                   Really got T!
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  (T	
  |	
  false	
  |	
  Exception)	
  MoveNext();	
  
}	
  
                                                 Got false?
                                               Really got void!
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  IEnumerator<T>	
  GetEnumerator();	
  
}	
  
                                               Every enumerator is disposable
	
  
interface	
  IEnumerator<out	
  T>	
  :	
  IDisposable	
  
{	
  
	
  	
  (T	
  |	
  void	
  |	
  Exception)	
  MoveNext();	
  
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  (IEnumerator<T>	
  &	
  IDisposable)	
  GetEnumerator();	
  
}	
  
                    Hypothe4cal	
  syntax	
  (“and”)	
  
	
  
interface	
  IEnumerator<out	
  T>	
  
{	
  
	
  	
  (T	
  |	
  void	
  |	
  Exception)	
  MoveNext();	
  
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  (IEnumerator<T>	
  &	
  IDisposable)	
  GetEnumerator();	
  
}	
  
                                                   Variance will flip!
	
  
interface	
  IEnumerator<out	
  T>	
  
{	
  
	
  	
  (T	
  |	
  void	
  |	
  Exception)	
  MoveNext();	
  
}	
  
                         Will rename too     This is really void
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  (IEnumerator<T>	
  &	
  IDisposable)	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumeratorDual<in	
  T>	
  
{	
  
	
  	
  void	
  	
  	
  OnNext(T	
  |	
  void	
  |	
  Exception);	
  
}	
  
                                                  Can encode as
                                                  three methods
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IEnumerable<out	
  T>	
  
{	
  
	
  	
  (IEnumerator<T>	
  &	
  IDisposable)	
  GetEnumerator();	
  
}	
  
	
  
interface	
  IEnumeratorDual<in	
  T>	
  
{	
                                                 Color of the
	
  	
  void	
  	
  	
  OnNext(T	
  value);	
       bikeshed (*)
	
  	
  void	
  	
  	
  OnCompleted();	
  
	
  	
  void	
  	
  	
  OnError(Exception	
  exception);	
  
}	
  
                    (*)	
  Visit	
  h^p://en.wikipedia.org/wiki/Color_of_the_bikeshed	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

                                           Will leave this
interface	
  IEnumerable<out	
  T>	
        part alone
{	
  
	
  	
  (IEnumerator<T>	
  &	
  IDisposable)	
  GetEnumerator();	
  
}	
                     This is the data
	
                          source                    Need to patch
interface	
  IObserver<in	
  T>	
                     this one up too
{	
  
	
  	
  void	
  	
  	
  OnNext(T	
  value);	
  
	
  	
  void	
  	
  	
  OnCompleted();	
  
	
  	
  void	
  	
  	
  OnError(Exception	
  exception);	
  
}	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

                                                            Color of the
interface	
  IEnumerableDual<out	
  T>	
                    bikeshed (*)
{	
  
	
  	
  IDisposable	
  SetObserver(IObserver<T>	
  observer);	
  
}	
  
	
  
interface	
  IObserver<in	
  T>	
  
{	
  
	
  	
  void	
  	
  	
  OnNext(T	
  value);	
  
	
  	
  void	
  	
  	
  OnCompleted();	
  
	
  	
  void	
  	
  	
  OnError(Exception	
  exception);	
  
}	
  
                   (*)	
  Visit	
  h^p://en.wikipedia.org/wiki/Color_of_the_bikeshed	
  
What’s	
  the	
  dual	
  of	
  IEnumerable?	
  

interface	
  IObservable<out	
  T>	
  
{	
  
	
  	
  IDisposable	
  Subscribe(IObserver<T>	
  observer);	
  
}	
  
	
  
interface	
  IObserver<in	
  T>	
  
{	
  
	
  	
  void	
  	
  	
  OnNext(T	
  value);	
  
	
  	
  void	
  	
  	
  OnCompleted();	
  
	
  	
  void	
  	
  	
  OnError(Exception	
  exception);	
  
}	
  
Essen,al	
  Interfaces	
  

interface	
  IObservable<out	
  T>	
  
{	
  
	
  	
  IDisposable	
  Subscribe(IObserver<T>	
  observer);	
  
}	
                                             C# 4.0
	
                                         contravariance
interface	
  IObserver<in	
  T>	
  
{	
  
                                                        You could get
	
  	
  void	
  	
  	
  OnNext(T	
  value);	
             flooded
	
  	
  void	
  	
  	
  OnError(Exception	
  ex);	
  
	
  	
  void	
  	
  	
  OnCompleted();	
  
}	
  
Essen,al	
  Interfaces	
  
                                                     	
  	
   ApplicaHon	
  
InteracHve	
  




                                     MoveNext	
  
                 Got	
  next?	
  




                                                                                    OnNext	
  




                                                                                                                     ReacHve	
  
                                                                                                 Have	
  next!	
  



                             IEnumerable<T>	
                                  IObservable<T>	
  
                             IEnumerator<T>	
                                   IObserver<T>	
  



                                                    Environment
Demo	
  
Geeng	
  Your	
  Observables	
  
                 OnCompleted
          .Empty<int>()           new	
  int[0]	
  

                   OnNext
          .Return(42)             new[]	
  {	
  42	
  }	
  

                        OnError
         .Throw<int>(ex)           Throwing	
  iterator	
  


          .Never<int>()
                                  Iterator	
  that	
  got	
  stuck	
  
Notion of time
Geeng	
  Your	
  Observables	
  


OnNext         OnError	
       OnCompleted	
  

                 OnNext(0)   OnNext(1)   OnNext(2)

         .Range(0, 3)



                  yield 0     yield 1     yield 2

         .Range(0, 3)
Geeng	
  Your	
  Observables	
  
    A variant with time notion                   Hypothetical anonymous
   exists (GenerateWithTime)                       iterator syntax in C#

o	
  =	
  Observable.Generate(	
              new IEnumerable int
	
  	
  	
  0,	
                             for int
	
  	
  	
  i	
  =>	
  i	
  <	
  10,	
  
	
  	
  	
  i	
  =>	
  i	
  +	
  1,	
  
	
  	
  	
  i	
  =>	
  i	
  *	
  i	
           yield	
  return	
  
);	
  
                  Asynchronou
                                                Synchronous
                             s
o.Subscribe(x	
  =>	
  {	
                 foreach var       in
	
  	
  	
  Console.WriteLine(x);	
           Console
});	
  
Geeng	
  Your	
  Observables	
  

IObservable<int>	
  o	
  =	
  Observable.Create<int>(observer	
  =>	
  {	
  
	
  	
  //	
  Assume	
  we	
  introduce	
  concurrency	
  (see	
  later)…	
  
	
  	
  observer.OnNext(42);	
  
	
  	
  observer.OnCompleted();	
  
	
  	
  return	
  ()	
  =>	
  {	
  /*	
  unsubscribe	
  action	
  */	
  };	
  
});	
  

IDisposable	
  subscription	
  =	
  o.Subscribe(	
  
	
  	
  onNext:	
  	
  	
  	
  	
  	
  x	
  	
  =>	
  {	
  Console.WriteLine("Next:	
  "	
  +	
  x);	
  },	
  
	
  	
  onError:	
  	
  	
  	
  	
  ex	
  =>	
  {	
  Console.WriteLine("Oops:	
  "	
  +	
  ex);	
  },	
  
	
  	
  onCompleted:	
  ()	
  =>	
  {	
  Console.WriteLine("Done");	
  }	
  
);	
  
                                                             C# doesn’t have anonymous interface
           C# 4.0 named                                      implementation, so we provide various
         parameter syntax                                     extension methods that take lambdas.
Geeng	
  Your	
  Observables	
  

IObservable<int>	
  o	
  =	
  Observable.Create<int>(observer	
  =>	
  {	
  
	
  	
  //	
  Assume	
  we	
  introduce	
  concurrency	
  (see	
  later)…	
  
	
  	
  observer.OnNext(42);	
  
	
  	
  observer.OnCompleted();	
  
	
  	
  return	
  ()	
  =>	
  {	
  /*	
  unsubscribe	
  action	
  */	
  };	
  
});	
  

IDisposable	
  subscription	
  =	
  o.Subscribe(	
  
	
  	
  onNext:	
  	
  	
  	
  	
  	
  x	
  	
  =>	
  {	
  Console.WriteLine("Next:	
  "	
  +	
  x);	
  },	
  
	
  	
  onError:	
  	
  	
  	
  	
  ex	
  =>	
  {	
  Console.WriteLine("Oops:	
  "	
  +	
  ex);	
  },	
  
	
  	
  onCompleted:	
  ()	
  =>	
  {	
  Console.WriteLine("Done");	
  }	
  
);	
  

Thread.Sleep(30000);	
  //	
  Main	
  thread	
  is	
  blocked…	
                                  F10
Geeng	
  Your	
  Observables	
  

IObservable<int>	
  o	
  =	
  Observable.Create<int>(observer	
  =>	
  {	
  
	
  	
  //	
  Assume	
  we	
  introduce	
  concurrency	
  (see	
  later)…	
  
	
  	
  observer.OnNext(42);	
  
	
  	
  observer.OnCompleted();	
  
	
  	
  return	
  ()	
  =>	
  {	
  /*	
  unsubscribe	
  action	
  */	
  };	
  
});	
  

IDisposable	
  subscription	
  =	
  o.Subscribe(	
  
	
  	
  onNext:	
  	
  	
  	
  	
  	
  x	
  	
  =>	
  {	
  Console.WriteLine("Next:	
  "	
  +	
  x);	
  },	
  
	
  	
  onError:	
  	
  	
  	
  	
  ex	
  =>	
  {	
  Console.WriteLine("Oops:	
  "	
  +	
  ex);	
  },	
  
	
  	
  onCompleted:	
  ()	
  =>	
  {	
  Console.WriteLine("Done");	
  }	
  
);	
  

Thread.Sleep(30000);	
  //	
  Main	
  thread	
  is	
  blocked…	
                                  F10
Geeng	
  Your	
  Observables	
  

IObservable<int>	
  o	
  =	
  Observable.Create<int>(observer	
  =>	
  {	
  
	
  	
  //	
  Assume	
  we	
  introduce	
  concurrency	
  (see	
  later)…	
  
	
  	
  observer.OnNext(42);	
  
	
  	
  observer.OnCompleted();	
  
	
  	
  return	
  ()	
  =>	
  {	
  /*	
  unsubscribe	
  action	
  */	
  };	
  
});	
  

IDisposable	
  subscription	
  =	
  o.Subscribe(	
  
	
  	
  onNext:	
  	
  	
  	
  	
  	
  x	
  	
  =>	
  {	
  Console.WriteLine("Next:	
  "	
  +	
  x);	
  },	
  
	
  	
  onError:	
  	
  	
  	
  	
  ex	
  =>	
  {	
  Console.WriteLine("Oops:	
  "	
  +	
  ex);	
  },	
  
	
  	
  onCompleted:	
  ()	
  =>	
  {	
  Console.WriteLine("Done");	
  }	
  
);	
  

Thread.Sleep(30000);	
  //	
  Main	
  thread	
  is	
  blocked…	
                                   F5
Geeng	
  Your	
  Observables	
  

IObservable<int>	
  o	
  =	
  Observable.Create<int>(observer	
  =>	
  {	
  
	
  	
  //	
  Assume	
  we	
  introduce	
  concurrency	
  (see	
  later)…	
  
	
  	
  observer.OnNext(42);	
  
	
  	
  observer.OnCompleted();	
  
	
  	
  return	
  ()	
  =>	
  {	
  /*	
  unsubscribe	
  action	
  */	
  };	
  
});	
                                                                         Breakpoint
                                                                                got hit
IDisposable	
  subscription	
  =	
  o.Subscribe(	
  
	
  	
  onNext:	
  	
  	
  	
  	
  	
  x	
  	
  =>	
  {	
  Console.WriteLine("Next:	
  "	
  +	
  x);	
  },	
  
	
  	
  onError:	
  	
  	
  	
  	
  ex	
  =>	
  {	
  Console.WriteLine("Oops:	
  "	
  +	
  ex);	
  },	
  
	
  	
  onCompleted:	
  ()	
  =>	
  {	
  Console.WriteLine("Done");	
  }	
  
);	
  

Thread.Sleep(30000);	
  //	
  Main	
  thread	
  is	
  blocked…	
  
Demo	
  
Bridging	
  Rx	
  with	
  the	
  World	
  

     How to pass around?     Hidden data source

form1.MouseMove += (sender, args) => {

     if (args.Location.X == args.Location.Y)
        // I’d like to raise another event
};
                       Lack of composition


form1.MouseMove -= /* what goes here? */
                  Resource
                 maintenance?
Bridging	
  Rx	
  with	
  the	
  World	
  

                              Source of Point
  Objects can be passed
                                  values
IObservable<Point> mouseMoves =
      Observable.FromEvent(frm, "MouseMove");
var filtered = mouseMoves
              .Where(pos => pos.X == pos.Y);

                    Can define operators

var subscription = filtered.Subscribe(…);
subscription.Dispose();
                Resource
               maintenance!
Bridging	
  Rx	
  with	
  the	
  World	
  

  	
   Exceptions?                                        Hidden data source
  	
  
  FileStream	
  fs	
  =	
  File.OpenRead("data.txt");	
  
  byte[]	
  bs	
  =	
  new	
  byte[1024];	
  
  fs.BeginRead(bs,	
  0,	
  bs.Length,	
   Really a method pair
  	
  	
  	
  	
  new	
  AsyncCallback(iar	
  =>	
  {	
  
  	
  	
  	
  	
  	
  	
  	
  int	
  bytesRead	
  =	
  fs.EndRead(iar);	
  
Cancel?
  	
  	
  	
  	
  	
  	
  	
  //	
  Do	
  something	
  with	
  bs[0..bytesRead-­‐1]	
  
  	
  	
  	
  	
  }),	
  
  	
  	
  	
  	
  null	
                   Lack of composition
  );	
                                                               Synchronous
                                State?                               completion?
Bridging	
  Rx	
  with	
  the	
  World	
  

FileStream	
  fs	
  =	
  File.OpenRead("data.txt");	
  
Func<byte[],	
  int,	
  int,	
  IObservable<int>>	
  read	
  =	
  
	
  
	
  	
  	
  Observable.FromAsyncPattern<byte[],	
  int,	
  int,	
  
	
  

	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  int>(	
  
	
  	
  	
  	
  	
  	
  fs.BeginRead,	
  fs.EndRead);	
  

byte[]	
  bs	
  =	
  new	
  byte[1024];	
  
read(bs,	
  0,	
  bs.Length).Subscribe(bytesRead	
  =>	
  {	
  
	
  	
  	
  	
  //	
  Do	
  something	
  with	
  bs[0..bytesRead-­‐1]	
  
});	
  
                                  Tip: a nicer wrapper can easily be
                                   made using various operators
Bridging	
  Rx	
  with	
  the	
  World	
  

 don’t	
  replace	
  




unify
             composiHonality	
  
           generic operators	
  


build	
  bridges!	
  
Bridging	
  Rx	
  with	
  the	
  World	
  

•  Cold	
  observables	
  
       var	
         Observable.Return

                   Triggered by subscription
	
  
          .Subscribe(                          )   //	
  Prints	
  42	
  
	
        .Subscribe(                          )   //	
  Prints	
  42	
  again	
  


•  Hot	
  observables	
  
       var            Observable.FromEvent MouseEventArgs
                                 "MouseMove"

                           Mouse events going
                           before subscription

                           Console
Demo	
  
Composi,on	
  and	
  Querying	
  




                                    Parameterization
      IScheduler	
                    of operators
var                .Return     Scheduler.ThreadPool
             Console
            Will run on the
          source’s scheduler
Composi,on	
  and	
  Querying	
  

           duality
    –  Convert	
  between	
  both	
  worlds	
  
        //	
  Introduces	
  concurrency	
  to	
  enumerate	
  and	
  signal…	
  
        var                                         .ToObservable();	
  

        //	
  Removes	
  concurrency	
  by	
  observing	
  and	
  yielding…	
  
        var                                         .ToEnumerable()

•  “Time-­‐centric”	
  reacHve	
  operators:	
  

                                                                      Race!

                  .Amb(              )
Composi,on	
  and	
  Querying	
  

                synchronize
                                   .Return     Scheduler.ThreadPool
                                             "Answer	
  =	
  "



IScheduler interface
•  WPF dispatcher
•  WinForms control
•  SynchronizationContext




             .ObserveOn(frm)	
  
     	
  	
                                  "Answer	
  =	
  "
Composi,on	
  and	
  Querying	
  

•  Observables	
  are	
  sources	
  of	
  data	
  
    –  Data	
  is	
  sent	
  to	
  you	
  (push	
  based)	
  
    –  Extra	
  (op,onal)	
  noHon	
  of	
  Hme	
  
•  Hence	
  we	
  can	
  query	
  over	
  them	
  
    //	
  Producing	
  an	
  IObservable<Point>	
  using	
  Select	
  
    var	
  mme	
  =	
  from	
  mm	
  in	
  Observable.FromEvent<MouseEventArgs>(	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  form,	
  “MouseMove”)	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  mm.EventArgs.Location;	
  
    	
  
    //	
  Filtering	
  for	
  the	
  first	
  bisector	
  using	
  Where	
  
    var	
  res	
  =	
  from	
  mm	
  in	
  mme	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  where	
  mm.X	
  ==	
  mm.Y	
  
    	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  mm;	
  
Composi,on	
  and	
  Querying	
  
                                            Asynchronou
                                              s request
   IObservable<string>

            TextChanged	
  
React                                Dictionary
                                    web service
Reaction
Reactive
Reactor
                         IObservable<DictionaryWord[]>

           Data binding
           on UI thread
Composi,on	
  and	
  Querying	
  

//	
  IObservable<string>	
  from	
  TextChanged	
  events	
  
var	
  changed	
  =	
  Observable.FromEvent<EventArgs>(txt,	
  "TextChanged");	
  
var	
  input	
  =	
  (from	
  text	
  in	
  changed	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  ((TextBox)text.Sender).Text);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .DistinctUntilChanged()	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .Throttle(TimeSpan.FromSeconds(1));	
  

//	
  Bridge	
  with	
  the	
  dictionary	
  web	
  service	
  
var	
  svc	
  =	
  new	
  DictServiceSoapClient();	
  
var	
  lookup	
  =	
  Observable.FromAsyncPattern<string,	
  DictionaryWord[]>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  (svc.BeginLookup,	
  svc.EndLookup);	
  

//	
  Compose	
  both	
  sources	
  using	
  SelectMany	
  
var	
  res	
  =	
  from	
  term	
  in	
  input	
  
                                                                                input.SelectMany(term	
  =>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  from	
  words	
  in	
  lookup(term)	
  
                                                                                      lookup(term))	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  words;	
  
Demo	
  
Composi,on	
  and	
  Querying	
  

Reactive|
Reacti|
React|
Reac|
Rea|
Re|
|
Reactiv|
R|               input

Reactive
Reaction
Reactive              Service	
  call	
  1	
  
Reactor

                                                 Service	
  call	
  2	
  


                  UI	
  data	
  binding	
  




 Source: http://scrapetv.com
Composi,on	
  and	
  Querying	
  

Reactive|
Reacti|
React|
Reac|
Rea|
Re|
|
Reactiv|
R|            input




                                                                     UnHl	
  
Reactive
                   Service	
  call	
  1	
  
                                               Take	
  


                                              Service	
  call	
  2	
  


            UI	
  data	
  binding	
  
Composi,on	
  and	
  Querying	
  

//	
  IObservable<string>	
  from	
  TextChanged	
  events	
  
var	
  changed	
  =	
  Observable.FromEvent<EventArgs>(txt,	
  "TextChanged");	
  
var	
  input	
  =	
  (from	
  text	
  in	
  changed	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  ((TextBox)text.Sender).Text);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .DistinctUntilChanged()	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .Throttle(TimeSpan.FromSeconds(1));	
  

//	
  Bridge	
  with	
  the	
  dictionary	
  web	
  service	
  
var	
  svc	
  =	
  new	
  DictServiceSoapClient();	
  
var	
  lookup	
  =	
  Observable.FromAsyncPattern<string,	
  DictionaryWord[]>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  (svc.BeginLookup,	
  svc.EndLookup);	
  
                                                                                                                   Very local fix
//	
  Compose	
  both	
  sources	
  using	
  SelectMany	
                                                                J
var	
  res	
  =	
  from	
  term	
  in	
  input	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  from	
  words	
  in	
  lookup(term).TakeUntil(input)	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  words;	
  
Composi,on	
  and	
  Querying	
  

//	
  IObservable<string>	
  from	
  TextChanged	
  events	
  
var	
  changed	
  =	
  Observable.FromEvent<EventArgs>(txt,	
  "TextChanged");	
  
var	
  input	
  =	
  (from	
  text	
  in	
  changed	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  ((TextBox)text.Sender).Text);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .DistinctUntilChanged()	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .Throttle(TimeSpan.FromSeconds(1));	
  

//	
  Bridge	
  with	
  the	
  dictionary	
  web	
  service	
  
var	
  svc	
  =	
  new	
  DictServiceSoapClient();	
  
var	
  lookup	
  =	
  Observable.FromAsyncPattern<string,	
  DictionaryWord[]>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  (svc.BeginLookup,	
  svc.EndLookup);	
  

//	
  Alternative	
  approach	
  for	
  composition	
  using:	
  
//	
  	
  	
  IObservable<T>	
  Switch<T>(IObservable<IObservable<T>>	
  sources)	
  
var	
  res	
  =	
  (from	
  term	
  in	
  input	
  
                                                                                  Hops from source
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  select	
  lookup(term)).Switch();	
  
                                                                                                                                 to source
Demo	
  
Mission	
  Accomplished	
  
Way	
  simpler	
  with	
  Rx	
                 (!  ◦  ")(#)  =  !("(#))



    Rx is a library for composing
   asynchronous and event-based
     programs using observable
              sequences.
                                                      Queries!	
  LINQ!	
  

                                                 •    .NET	
  3.5	
  SP1	
  and	
  4.0	
  
                                                 •    Silverlight	
  3	
  and	
  4	
  
                                                 •    XNA	
  3.1	
  for	
  XBOX	
  and	
  Zune	
  
                                                 •    Windows	
  Phone	
  7	
  
                                                 •    JavaScript	
  (RxJS)	
  

                          MSDN	
  Data	
  Developer	
  Center	
                    NuGet	
  
Related	
  Content	
  
•  Hands-­‐on	
  Labs	
  
   –  Two	
  flavors:	
  
         •  Curing	
  the	
  asynchronous	
  blues	
  with	
  the	
  Reac,ve	
  Extensions	
  (Rx)	
  for	
  .NET	
  
         •  Curing	
  the	
  asynchronous	
  blues	
  with	
  the	
  Reac,ve	
  Extensions	
  (Rx)	
  for	
  JavaScript	
  
   –  Both	
  can	
  be	
  found	
  via	
  the	
  Rx	
  forums	
  
•  Rx	
  team	
  web	
  presence	
  
    –    Rx	
  team	
  blog	
  –	
  h^p://blogs.msdn.com/rxteam	
  
    –    DevLabs	
  –	
  h^p://msdn.microso'.com/en-­‐us/devlabs/ee794896.aspx	
  
    –    MSDN	
  forums	
  –	
  h^p://social.msdn.microso'.com/Forums/en-­‐US/rx	
  
    –    Channel9	
  –	
  h^p://channel9.msdn.com/Tags/Rx	
  
Thanks!	
  
 Bart	
  J.F.	
  De	
  Smet	
  

More Related Content

What's hot

C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
xu liwei
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
Taisuke Oe
 

What's hot (20)

Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
 
MTPLs
MTPLsMTPLs
MTPLs
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Digital Electronics Basics by Er. Swapnil Kaware
Digital Electronics Basics by Er. Swapnil KawareDigital Electronics Basics by Er. Swapnil Kaware
Digital Electronics Basics by Er. Swapnil Kaware
 
C++11
C++11C++11
C++11
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 

Viewers also liked

버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
민태 김
 

Viewers also liked (9)

외계어 스터디 4/5 Event & Library
외계어 스터디 4/5 Event & Library외계어 스터디 4/5 Event & Library
외계어 스터디 4/5 Event & Library
 
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬2013 빅데이터 및 API 기술 현황과 전망- 윤석찬
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬
 
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
 
Git - Level 2
Git - Level 2Git - Level 2
Git - Level 2
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
 
초보자를 위한 정규 표현식 가이드 (자바스크립트 기준)
초보자를 위한 정규 표현식 가이드 (자바스크립트 기준)초보자를 위한 정규 표현식 가이드 (자바스크립트 기준)
초보자를 위한 정규 표현식 가이드 (자바스크립트 기준)
 

Similar to Rx: Curing Your Asynchronous Programming Blues | QCon London

A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
Julien Wetterwald
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 

Similar to Rx: Curing Your Asynchronous Programming Blues | QCon London (20)

Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
pdx-react-observables
pdx-react-observablespdx-react-observables
pdx-react-observables
 
Testing for share
Testing for share Testing for share
Testing for share
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
C# programming
C# programming C# programming
C# programming
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixir
 
Intro to RX
Intro to RXIntro to RX
Intro to RX
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 
.net code: some ideas to improve yours
.net code: some ideas to improve yours.net code: some ideas to improve yours
.net code: some ideas to improve yours
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Renaming Tokens
Renaming TokensRenaming Tokens
Renaming Tokens
 

Recently uploaded

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
Muhammad Subhan
 

Recently uploaded (20)

How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
 

Rx: Curing Your Asynchronous Programming Blues | QCon London

  • 1. Rx:  Curing  your  Asynchronous   Programming  Blues   Bart  J.F.  De  Smet   Microso'  Corpora,on   bartde@microso'.com  
  • 2. Why  Should  I  Care?   GPS   RSS            feeds   Stock   ,ckers   Social   media   Server  management  
  • 3. Mission  Statement   Too  hard  today!   (!  ◦  ")(#)  =  !("(#)) Rx is a library for composing asynchronous and event-based programs using observable sequences. Queries?  LINQ?   •  .NET  3.5  SP1  and  4.0   •  Silverlight  3  and  4   •  XNA  3.1  for  XBOX  and  Zune   •  Windows  Phone  7   •  JavaScript  (RxJS)   MSDN  Data  Developer  Center   NuGet  
  • 4. Essen,al  Interfaces   interface  IEnumerable<out  T>   {          IEnumerator<T>  GetEnumerator();   }   C# 4.0 covariance interface  IEnumerator<out  T>  :  IDisposable   {   You could get        bool      MoveNext();   stuck        T            Current  {  get;  }          void      Reset();   }  
  • 5. Essen,al  Interfaces   (WaiHng  to  move  next)   C# 4.0 covariance moving  on   You could get stuck
  • 6. Mathema,cal  Duality   Because  the  Dutch  are  (said  to  be)  cheap   –  Electricity:    inductor  and  capacitor   –  Logic:    De  Morgan’s  Law   ¬(%∧&)≡¬%∨¬&   ¬(%∨&)≡¬%∧¬&   –  Programming?  
  • 7. What’s  the  dual  of  IEnumerable?   The  recipe  to  dualiza,on   h^p://en.wikipedia.org/wiki/Dual_(category_theory) Reversing arrows… Input becomes output and vice versa Making  a  U-­‐turn   in  synchrony  
  • 8. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      bool    MoveNext();      T          Current  {  get;  }   Properties    void    Reset();   are methods }  
  • 9. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      bool    MoveNext();      T          GetCurrent();      void    Reset();   A historical mishap }  
  • 10. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      bool    MoveNext();   No checked    T          GetCurrent();   exceptions in .NET / C# }  
  • 11. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      bool    MoveNext()  throws  Exception;      T          GetCurrent();   }  
  • 12. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      bool    MoveNext()  throws  Exception;      T          GetCurrent();   This is an }   output too!
  • 13. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      (bool  |  Exception)  MoveNext();      T          GetCurrent();   Discriminated  union   }   Really only two type  (“or”)   values
  • 14. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      (true  |  false  |  Exception)  MoveNext();      T          GetCurrent();   }   Got true? Really got T!
  • 15. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }     interface  IEnumerator<out  T>  :  IDisposable   {      (T  |  false  |  Exception)  MoveNext();   }   Got false? Really got void!
  • 16. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      IEnumerator<T>  GetEnumerator();   }   Every enumerator is disposable   interface  IEnumerator<out  T>  :  IDisposable   {      (T  |  void  |  Exception)  MoveNext();   }  
  • 17. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      (IEnumerator<T>  &  IDisposable)  GetEnumerator();   }   Hypothe4cal  syntax  (“and”)     interface  IEnumerator<out  T>   {      (T  |  void  |  Exception)  MoveNext();   }  
  • 18. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      (IEnumerator<T>  &  IDisposable)  GetEnumerator();   }   Variance will flip!   interface  IEnumerator<out  T>   {      (T  |  void  |  Exception)  MoveNext();   }   Will rename too This is really void
  • 19. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      (IEnumerator<T>  &  IDisposable)  GetEnumerator();   }     interface  IEnumeratorDual<in  T>   {      void      OnNext(T  |  void  |  Exception);   }   Can encode as three methods
  • 20. What’s  the  dual  of  IEnumerable?   interface  IEnumerable<out  T>   {      (IEnumerator<T>  &  IDisposable)  GetEnumerator();   }     interface  IEnumeratorDual<in  T>   {   Color of the    void      OnNext(T  value);   bikeshed (*)    void      OnCompleted();      void      OnError(Exception  exception);   }   (*)  Visit  h^p://en.wikipedia.org/wiki/Color_of_the_bikeshed  
  • 21. What’s  the  dual  of  IEnumerable?   Will leave this interface  IEnumerable<out  T>   part alone {      (IEnumerator<T>  &  IDisposable)  GetEnumerator();   }   This is the data   source Need to patch interface  IObserver<in  T>   this one up too {      void      OnNext(T  value);      void      OnCompleted();      void      OnError(Exception  exception);   }  
  • 22. What’s  the  dual  of  IEnumerable?   Color of the interface  IEnumerableDual<out  T>   bikeshed (*) {      IDisposable  SetObserver(IObserver<T>  observer);   }     interface  IObserver<in  T>   {      void      OnNext(T  value);      void      OnCompleted();      void      OnError(Exception  exception);   }   (*)  Visit  h^p://en.wikipedia.org/wiki/Color_of_the_bikeshed  
  • 23. What’s  the  dual  of  IEnumerable?   interface  IObservable<out  T>   {      IDisposable  Subscribe(IObserver<T>  observer);   }     interface  IObserver<in  T>   {      void      OnNext(T  value);      void      OnCompleted();      void      OnError(Exception  exception);   }  
  • 24. Essen,al  Interfaces   interface  IObservable<out  T>   {      IDisposable  Subscribe(IObserver<T>  observer);   }   C# 4.0   contravariance interface  IObserver<in  T>   {   You could get    void      OnNext(T  value);   flooded    void      OnError(Exception  ex);      void      OnCompleted();   }  
  • 25. Essen,al  Interfaces       ApplicaHon   InteracHve   MoveNext   Got  next?   OnNext   ReacHve   Have  next!   IEnumerable<T>   IObservable<T>   IEnumerator<T>   IObserver<T>   Environment
  • 27. Geeng  Your  Observables   OnCompleted .Empty<int>() new  int[0]   OnNext .Return(42) new[]  {  42  }   OnError .Throw<int>(ex) Throwing  iterator   .Never<int>() Iterator  that  got  stuck   Notion of time
  • 28. Geeng  Your  Observables   OnNext OnError   OnCompleted   OnNext(0) OnNext(1) OnNext(2) .Range(0, 3) yield 0 yield 1 yield 2 .Range(0, 3)
  • 29. Geeng  Your  Observables   A variant with time notion Hypothetical anonymous exists (GenerateWithTime) iterator syntax in C# o  =  Observable.Generate(   new IEnumerable int      0,   for int      i  =>  i  <  10,        i  =>  i  +  1,        i  =>  i  *  i   yield  return   );   Asynchronou Synchronous s o.Subscribe(x  =>  {   foreach var in      Console.WriteLine(x);   Console });  
  • 30. Geeng  Your  Observables   IObservable<int>  o  =  Observable.Create<int>(observer  =>  {      //  Assume  we  introduce  concurrency  (see  later)…      observer.OnNext(42);      observer.OnCompleted();      return  ()  =>  {  /*  unsubscribe  action  */  };   });   IDisposable  subscription  =  o.Subscribe(      onNext:            x    =>  {  Console.WriteLine("Next:  "  +  x);  },      onError:          ex  =>  {  Console.WriteLine("Oops:  "  +  ex);  },      onCompleted:  ()  =>  {  Console.WriteLine("Done");  }   );   C# doesn’t have anonymous interface C# 4.0 named implementation, so we provide various parameter syntax extension methods that take lambdas.
  • 31. Geeng  Your  Observables   IObservable<int>  o  =  Observable.Create<int>(observer  =>  {      //  Assume  we  introduce  concurrency  (see  later)…      observer.OnNext(42);      observer.OnCompleted();      return  ()  =>  {  /*  unsubscribe  action  */  };   });   IDisposable  subscription  =  o.Subscribe(      onNext:            x    =>  {  Console.WriteLine("Next:  "  +  x);  },      onError:          ex  =>  {  Console.WriteLine("Oops:  "  +  ex);  },      onCompleted:  ()  =>  {  Console.WriteLine("Done");  }   );   Thread.Sleep(30000);  //  Main  thread  is  blocked…   F10
  • 32. Geeng  Your  Observables   IObservable<int>  o  =  Observable.Create<int>(observer  =>  {      //  Assume  we  introduce  concurrency  (see  later)…      observer.OnNext(42);      observer.OnCompleted();      return  ()  =>  {  /*  unsubscribe  action  */  };   });   IDisposable  subscription  =  o.Subscribe(      onNext:            x    =>  {  Console.WriteLine("Next:  "  +  x);  },      onError:          ex  =>  {  Console.WriteLine("Oops:  "  +  ex);  },      onCompleted:  ()  =>  {  Console.WriteLine("Done");  }   );   Thread.Sleep(30000);  //  Main  thread  is  blocked…   F10
  • 33. Geeng  Your  Observables   IObservable<int>  o  =  Observable.Create<int>(observer  =>  {      //  Assume  we  introduce  concurrency  (see  later)…      observer.OnNext(42);      observer.OnCompleted();      return  ()  =>  {  /*  unsubscribe  action  */  };   });   IDisposable  subscription  =  o.Subscribe(      onNext:            x    =>  {  Console.WriteLine("Next:  "  +  x);  },      onError:          ex  =>  {  Console.WriteLine("Oops:  "  +  ex);  },      onCompleted:  ()  =>  {  Console.WriteLine("Done");  }   );   Thread.Sleep(30000);  //  Main  thread  is  blocked…   F5
  • 34. Geeng  Your  Observables   IObservable<int>  o  =  Observable.Create<int>(observer  =>  {      //  Assume  we  introduce  concurrency  (see  later)…      observer.OnNext(42);      observer.OnCompleted();      return  ()  =>  {  /*  unsubscribe  action  */  };   });   Breakpoint got hit IDisposable  subscription  =  o.Subscribe(      onNext:            x    =>  {  Console.WriteLine("Next:  "  +  x);  },      onError:          ex  =>  {  Console.WriteLine("Oops:  "  +  ex);  },      onCompleted:  ()  =>  {  Console.WriteLine("Done");  }   );   Thread.Sleep(30000);  //  Main  thread  is  blocked…  
  • 36. Bridging  Rx  with  the  World   How to pass around? Hidden data source form1.MouseMove += (sender, args) => { if (args.Location.X == args.Location.Y) // I’d like to raise another event }; Lack of composition form1.MouseMove -= /* what goes here? */ Resource maintenance?
  • 37.
  • 38. Bridging  Rx  with  the  World   Source of Point Objects can be passed values IObservable<Point> mouseMoves = Observable.FromEvent(frm, "MouseMove"); var filtered = mouseMoves .Where(pos => pos.X == pos.Y); Can define operators var subscription = filtered.Subscribe(…); subscription.Dispose(); Resource maintenance!
  • 39. Bridging  Rx  with  the  World     Exceptions? Hidden data source   FileStream  fs  =  File.OpenRead("data.txt");   byte[]  bs  =  new  byte[1024];   fs.BeginRead(bs,  0,  bs.Length,   Really a method pair        new  AsyncCallback(iar  =>  {                int  bytesRead  =  fs.EndRead(iar);   Cancel?              //  Do  something  with  bs[0..bytesRead-­‐1]          }),          null   Lack of composition );   Synchronous State? completion?
  • 40. Bridging  Rx  with  the  World   FileStream  fs  =  File.OpenRead("data.txt");   Func<byte[],  int,  int,  IObservable<int>>  read  =          Observable.FromAsyncPattern<byte[],  int,  int,                                                                  int>(              fs.BeginRead,  fs.EndRead);   byte[]  bs  =  new  byte[1024];   read(bs,  0,  bs.Length).Subscribe(bytesRead  =>  {          //  Do  something  with  bs[0..bytesRead-­‐1]   });   Tip: a nicer wrapper can easily be made using various operators
  • 41. Bridging  Rx  with  the  World   don’t  replace   unify composiHonality   generic operators   build  bridges!  
  • 42. Bridging  Rx  with  the  World   •  Cold  observables   var   Observable.Return Triggered by subscription   .Subscribe( ) //  Prints  42     .Subscribe( ) //  Prints  42  again   •  Hot  observables   var Observable.FromEvent MouseEventArgs "MouseMove" Mouse events going before subscription Console
  • 44. Composi,on  and  Querying   Parameterization IScheduler   of operators var .Return Scheduler.ThreadPool Console Will run on the source’s scheduler
  • 45. Composi,on  and  Querying   duality –  Convert  between  both  worlds   //  Introduces  concurrency  to  enumerate  and  signal…   var .ToObservable();   //  Removes  concurrency  by  observing  and  yielding…   var .ToEnumerable() •  “Time-­‐centric”  reacHve  operators:   Race! .Amb( )
  • 46. Composi,on  and  Querying   synchronize .Return Scheduler.ThreadPool "Answer  =  " IScheduler interface •  WPF dispatcher •  WinForms control •  SynchronizationContext .ObserveOn(frm)       "Answer  =  "
  • 47. Composi,on  and  Querying   •  Observables  are  sources  of  data   –  Data  is  sent  to  you  (push  based)   –  Extra  (op,onal)  noHon  of  Hme   •  Hence  we  can  query  over  them   //  Producing  an  IObservable<Point>  using  Select   var  mme  =  from  mm  in  Observable.FromEvent<MouseEventArgs>(                                                    form,  “MouseMove”)                      select  mm.EventArgs.Location;     //  Filtering  for  the  first  bisector  using  Where   var  res  =  from  mm  in  mme                      where  mm.X  ==  mm.Y                      select  mm;  
  • 48. Composi,on  and  Querying   Asynchronou s request IObservable<string> TextChanged   React Dictionary web service Reaction Reactive Reactor IObservable<DictionaryWord[]> Data binding on UI thread
  • 49. Composi,on  and  Querying   //  IObservable<string>  from  TextChanged  events   var  changed  =  Observable.FromEvent<EventArgs>(txt,  "TextChanged");   var  input  =  (from  text  in  changed                            select  ((TextBox)text.Sender).Text);                          .DistinctUntilChanged()                          .Throttle(TimeSpan.FromSeconds(1));   //  Bridge  with  the  dictionary  web  service   var  svc  =  new  DictServiceSoapClient();   var  lookup  =  Observable.FromAsyncPattern<string,  DictionaryWord[]>                                                                    (svc.BeginLookup,  svc.EndLookup);   //  Compose  both  sources  using  SelectMany   var  res  =  from  term  in  input   input.SelectMany(term  =>                      from  words  in  lookup(term)   lookup(term))                      select  words;  
  • 51. Composi,on  and  Querying   Reactive| Reacti| React| Reac| Rea| Re| | Reactiv| R| input Reactive Reaction Reactive Service  call  1   Reactor Service  call  2   UI  data  binding   Source: http://scrapetv.com
  • 52. Composi,on  and  Querying   Reactive| Reacti| React| Reac| Rea| Re| | Reactiv| R| input UnHl   Reactive Service  call  1   Take   Service  call  2   UI  data  binding  
  • 53. Composi,on  and  Querying   //  IObservable<string>  from  TextChanged  events   var  changed  =  Observable.FromEvent<EventArgs>(txt,  "TextChanged");   var  input  =  (from  text  in  changed                            select  ((TextBox)text.Sender).Text);                          .DistinctUntilChanged()                          .Throttle(TimeSpan.FromSeconds(1));   //  Bridge  with  the  dictionary  web  service   var  svc  =  new  DictServiceSoapClient();   var  lookup  =  Observable.FromAsyncPattern<string,  DictionaryWord[]>                                                                    (svc.BeginLookup,  svc.EndLookup);   Very local fix //  Compose  both  sources  using  SelectMany   J var  res  =  from  term  in  input                      from  words  in  lookup(term).TakeUntil(input)                      select  words;  
  • 54. Composi,on  and  Querying   //  IObservable<string>  from  TextChanged  events   var  changed  =  Observable.FromEvent<EventArgs>(txt,  "TextChanged");   var  input  =  (from  text  in  changed                            select  ((TextBox)text.Sender).Text);                          .DistinctUntilChanged()                          .Throttle(TimeSpan.FromSeconds(1));   //  Bridge  with  the  dictionary  web  service   var  svc  =  new  DictServiceSoapClient();   var  lookup  =  Observable.FromAsyncPattern<string,  DictionaryWord[]>                                                                    (svc.BeginLookup,  svc.EndLookup);   //  Alternative  approach  for  composition  using:   //      IObservable<T>  Switch<T>(IObservable<IObservable<T>>  sources)   var  res  =  (from  term  in  input   Hops from source                      select  lookup(term)).Switch();   to source
  • 56. Mission  Accomplished   Way  simpler  with  Rx   (!  ◦  ")(#)  =  !("(#)) Rx is a library for composing asynchronous and event-based programs using observable sequences. Queries!  LINQ!   •  .NET  3.5  SP1  and  4.0   •  Silverlight  3  and  4   •  XNA  3.1  for  XBOX  and  Zune   •  Windows  Phone  7   •  JavaScript  (RxJS)   MSDN  Data  Developer  Center   NuGet  
  • 57. Related  Content   •  Hands-­‐on  Labs   –  Two  flavors:   •  Curing  the  asynchronous  blues  with  the  Reac,ve  Extensions  (Rx)  for  .NET   •  Curing  the  asynchronous  blues  with  the  Reac,ve  Extensions  (Rx)  for  JavaScript   –  Both  can  be  found  via  the  Rx  forums   •  Rx  team  web  presence   –  Rx  team  blog  –  h^p://blogs.msdn.com/rxteam   –  DevLabs  –  h^p://msdn.microso'.com/en-­‐us/devlabs/ee794896.aspx   –  MSDN  forums  –  h^p://social.msdn.microso'.com/Forums/en-­‐US/rx   –  Channel9  –  h^p://channel9.msdn.com/Tags/Rx  
  • 58. Thanks!   Bart  J.F.  De  Smet