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

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]Chris Adamson
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap courseMartin Logan
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
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?Federico Tomassetti
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed 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): Day1Taisuke Oe
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statementsIntro C# Book
 
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?Kevin Pilch
 
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 KawareProf. Swapnil V. Kaware
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Featurestarun308
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 

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

외계어 스터디 4/5 Event & Library
외계어 스터디 4/5 Event & Library외계어 스터디 4/5 Event & Library
외계어 스터디 4/5 Event & Library민태 김
 
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬2013 빅데이터 및 API 기술 현황과 전망- 윤석찬
2013 빅데이터 및 API 기술 현황과 전망- 윤석찬Channy Yun
 
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스민태 김
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기Jong Wook Kim
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
버전관리를 들어본적 없는 사람들을 위한 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

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) Datagreenwop
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
pdx-react-observables
pdx-react-observablespdx-react-observables
pdx-react-observablesIan Irvine
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
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 wrongJulien Wetterwald
 
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#Juan Pablo
 
Introduction to Elixir
Introduction to ElixirIntroduction to Elixir
Introduction to Elixirbrien_wankel
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
C Programming Language
C Programming LanguageC Programming Language
C Programming LanguageRTS Tech
 
.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 yoursCarlos Lopes
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malikOshal Shah
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malikOshal Shah
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malikOshal Shah
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Renaming Tokens
Renaming TokensRenaming Tokens
Renaming Tokensyanamm
 

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

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Recently uploaded (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.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