SlideShare uma empresa Scribd logo
1 de 26
1
                         Introduction to Reactive Extensions




Peter Goodman

An Introduction to Reactive
Extensions
2
                    Introduction to Reactive Extensions




What are Reactive Extensions?
3
                    Introduction to Reactive Extensions




What are Reactive Extensions?
4
                    Introduction to Reactive Extensions




What are Reactive Extensions?
5
                    Introduction to Reactive Extensions




What are Reactive Extensions?
6
                                     Introduction to Reactive Extensions



Events in .Net

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

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




form1.MouseMove -= /* what goes here? */
7
                                      Introduction to Reactive Extensions



Collections are Enumerables
interface IEnumerable<out T>
{
    IEnumerator<T> GetEnumerator();
}

interface IEnumerator<out T> : IDisposable
{
    bool   MoveNext();
    T      Current { get; }
    void   Reset();
}
8
                                                            Introduction to Reactive Extensions


What if events were collections?
  Collection




Move Next   Move Next   Move Next   Move Next   Move Next       Move Next


  Event Stream


                                                                                            TIME


OnNext      OnNext      OnNext      OnNext      OnNext         OnNext
9
                                    Introduction to Reactive Extensions


Observables
interface IObservable<out T>
{
    IDisposable Subscribe(IObserver<T> observer);
}

interface IObserver<in T>
{
    void   OnNext(T value);
    void   OnError(Exception ex);
    void   OnCompleted();
}
10
                                                                   Introduction to Reactive Extensions

              Summary Push vs Pull
                                       Application
Interactive




                           MoveNext




                                                                                                         Reactive
               Got next?




                                                          OnNext
                                                                              Have next!



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



                                      Environment
11
                                    Introduction to Reactive Extensions


Creating Observables - Primitive
                  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
12
                                Introduction to Reactive Extensions




Creating Observables - Range

              OnNext(0)   OnNext(1)           OnNext(2)
      .Range(0, 3)



               yield 0     yield 1                yield 2
      .Range(0, 3)
13
                                        Introduction to Reactive Extensions


 Generating values and Subscribing
   A variant with time notion         Hypothetical anonymous
  exists (GenerateWithTime)             iterator syntax in C#

o = Observable.Generate(        e = new IEnumerable<int> {
   0,                              for (int i = 0;
   i => i < 10,                         i < 10;
   i => i + 1,                          i++)
   i => i * i                        yield return i * i;
);
                                };
            Asynchronous                   Synchronous

o.Subscribe(x => {              foreach (var x in e) {
   Console.WriteLine(x);           Console.WriteLine(x);
});                             }
14
                                                Introduction to Reactive Extensions



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

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




DEMO
Generating events and subscribing to them
16
                                               Introduction to Reactive Extensions



Observable Querying
 Observables are sources of data
   Data is sent to you (push based)
   Extra (optional) notion of time.


 Hence we can query over them
// Producing an IObservable<Point> using Select
var       from    in Observable           MouseEventArgs

           select                      .Location

// Filtering for the first bisector using Where
var       from    in
          where
          select
17
                                      Introduction to Reactive Extensions




DEMO
Querying, Composition and introducing Concurrency
18
                                              Introduction to Reactive Extensions



Introducing Asynchrony

 An Asynchronous operation can be thought of as an
  Observable that returns a single value and completes.

 FromAsync
   Takes an APM method pair (BeginExecute, EndExecute) and
    creates an Observable


 ToAsync
   Takes a method and creates an Observable (Like TPL)
19
                                                   Introduction to Reactive Extensions




Introducing Concurrency
 Many operators in Rx introduce Concurrency
     Throttle
     Interval
     Delay
     BufferWithTime

 Generally they provide an overload to supply a Scheduler
     ImmediateScheduler – Static Immediate
     CurrentThreadScheduler – Placed on a queue for the current thread
     NewThreadScheduler – Spawn a new Thread
     DispatcherScheduler - Silverlight
     TaskPoolScheduler - TPL
     ThreadPoolScheduler
20
                                            Introduction to Reactive Extensions




    Concurrency and Synchronization
•
    var     Observable.Return         Scheduler.ThreadPool
                                    "         "




•
      .ObserveOnDispatcher()
                                "           "
21
                  Introduction to Reactive Extensions




DEMO
Synchronization
22
                                 Introduction to Reactive Extensions



Rx for JavaScript (RxJS)
 Parity with Rx for .NET
   Set of operators
   Taming asynchronous JS
 JavaScript-specific bindings
     jQuery
     ExtJS
     Dojo
     Prototype
     YUI3
     MooTools
     Bing APIs
23
                    Introduction to Reactive Extensions




DEMO
Rx for JavaScript
24
                      Introduction to Reactive Extensions




Reactive Extensions

Questions?
25
                                  Introduction to Reactive Extensions




Resources
 MSDN

 Bart de Smet / Rx (Channel 9)

 Reactive UI

 Pushqa / SignalR
26
                            Introduction to Reactive Extensions




Contact
 pete@petegoo.com

 http://blog.petegoo.com

 Twitter: @petegoo

Mais conteúdo relacionado

Semelhante a Introduction to Reactive Extensions

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUIkiahiska
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no AndroidGuilherme Branco
 
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Ivan Čukić
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive ProgrammingTom Bulatewicz, PhD
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingBeauLiu
 
Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Rory Preddy
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVMNetesh Kumar
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Reactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event ProcessingReactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event ProcessingYoshifumi Kawai
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineering
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineeringNSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineering
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineeringNoSuchCon
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJCoen De Roover
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programmingDwi Randy Herdinanto
 

Semelhante a Introduction to Reactive Extensions (20)

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
 
Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
 
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Reactive x
Reactive xReactive x
Reactive x
 
Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Reactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event ProcessingReactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event Processing
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineering
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineeringNSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineering
NSC #2 - D1 01 - Rolf Rolles - Program synthesis in reverse engineering
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJ
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programming
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Introduction to Reactive Extensions

  • 1. 1 Introduction to Reactive Extensions Peter Goodman An Introduction to Reactive Extensions
  • 2. 2 Introduction to Reactive Extensions What are Reactive Extensions?
  • 3. 3 Introduction to Reactive Extensions What are Reactive Extensions?
  • 4. 4 Introduction to Reactive Extensions What are Reactive Extensions?
  • 5. 5 Introduction to Reactive Extensions What are Reactive Extensions?
  • 6. 6 Introduction to Reactive Extensions Events in .Net form1.MouseMove += (sender, args) => { if (args.Location.X == args.Location.Y) // I’d like to raise another event }; form1.MouseMove -= /* what goes here? */
  • 7. 7 Introduction to Reactive Extensions Collections are Enumerables interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> : IDisposable { bool MoveNext(); T Current { get; } void Reset(); }
  • 8. 8 Introduction to Reactive Extensions What if events were collections?  Collection Move Next Move Next Move Next Move Next Move Next Move Next  Event Stream TIME OnNext OnNext OnNext OnNext OnNext OnNext
  • 9. 9 Introduction to Reactive Extensions Observables interface IObservable<out T> { IDisposable Subscribe(IObserver<T> observer); } interface IObserver<in T> { void OnNext(T value); void OnError(Exception ex); void OnCompleted(); }
  • 10. 10 Introduction to Reactive Extensions Summary Push vs Pull Application Interactive MoveNext Reactive Got next? OnNext Have next! IEnumerable<T> IObservable<T> IEnumerator<T> IObserver<T> Environment
  • 11. 11 Introduction to Reactive Extensions Creating Observables - Primitive 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
  • 12. 12 Introduction to Reactive Extensions Creating Observables - Range OnNext(0) OnNext(1) OnNext(2) .Range(0, 3) yield 0 yield 1 yield 2 .Range(0, 3)
  • 13. 13 Introduction to Reactive Extensions Generating values and Subscribing A variant with time notion Hypothetical anonymous exists (GenerateWithTime) iterator syntax in C# o = Observable.Generate( e = new IEnumerable<int> { 0, for (int i = 0; i => i < 10, i < 10; i => i + 1, i++) i => i * i yield return i * i; ); }; Asynchronous Synchronous o.Subscribe(x => { foreach (var x in e) { Console.WriteLine(x); Console.WriteLine(x); }); }
  • 14. 14 Introduction to Reactive Extensions Subscribing IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } );
  • 15. 15 Introduction to Reactive Extensions DEMO Generating events and subscribing to them
  • 16. 16 Introduction to Reactive Extensions Observable Querying  Observables are sources of data  Data is sent to you (push based)  Extra (optional) notion of time.  Hence we can query over them // Producing an IObservable<Point> using Select var from in Observable MouseEventArgs select .Location // Filtering for the first bisector using Where var from in where select
  • 17. 17 Introduction to Reactive Extensions DEMO Querying, Composition and introducing Concurrency
  • 18. 18 Introduction to Reactive Extensions Introducing Asynchrony  An Asynchronous operation can be thought of as an Observable that returns a single value and completes.  FromAsync  Takes an APM method pair (BeginExecute, EndExecute) and creates an Observable  ToAsync  Takes a method and creates an Observable (Like TPL)
  • 19. 19 Introduction to Reactive Extensions Introducing Concurrency  Many operators in Rx introduce Concurrency  Throttle  Interval  Delay  BufferWithTime  Generally they provide an overload to supply a Scheduler  ImmediateScheduler – Static Immediate  CurrentThreadScheduler – Placed on a queue for the current thread  NewThreadScheduler – Spawn a new Thread  DispatcherScheduler - Silverlight  TaskPoolScheduler - TPL  ThreadPoolScheduler
  • 20. 20 Introduction to Reactive Extensions Concurrency and Synchronization • var Observable.Return Scheduler.ThreadPool " " • .ObserveOnDispatcher() " "
  • 21. 21 Introduction to Reactive Extensions DEMO Synchronization
  • 22. 22 Introduction to Reactive Extensions Rx for JavaScript (RxJS)  Parity with Rx for .NET  Set of operators  Taming asynchronous JS  JavaScript-specific bindings  jQuery  ExtJS  Dojo  Prototype  YUI3  MooTools  Bing APIs
  • 23. 23 Introduction to Reactive Extensions DEMO Rx for JavaScript
  • 24. 24 Introduction to Reactive Extensions Reactive Extensions Questions?
  • 25. 25 Introduction to Reactive Extensions Resources  MSDN  Bart de Smet / Rx (Channel 9)  Reactive UI  Pushqa / SignalR
  • 26. 26 Introduction to Reactive Extensions Contact  pete@petegoo.com  http://blog.petegoo.com  Twitter: @petegoo

Notas do Editor

  1. Who am I?Rx was developed by the Cloud Programmability Team
  2. - Composing gives us a hint at the Linq style fluent API
  3. Async and event-based programs. Recent initiatives including TPL, async/await etc
  4. You can’t pass an event aroundThe syntax is very unique and requires cleaning up of subscriptionsYou can’t compose events into new events easily.
  5. Lets look at an ordinary collection in .NetNotice in IEnumerable we FETCH an EnumeratorMoveNext pulls the next value from the collection synchronously into Current. It could have just as easily returned the current value from MoveNextReset is an oddity of historyWe are done when there are no more items and MoveNext returns true
  6. Observables turn the whole thing on it’s headNotice in Iobservable we get FED an ObserverOnNext pushed the next value from onto the collection asynchronously. OnError occurs when an exception has happened.OnCompleted happens when there are no more items
  7. Observable.Return(42).Subscribe(Console.WriteLine)Observable.Range(0,20). Subscribe(Console.WriteLine)Observable.Generate( 0,i =&gt; i &lt; 20, i =&gt; i+1, i =&gt; i*i) .Subscribe(Console.WriteLine);Observable.Generate( 0,i =&gt; i &lt; 20, i =&gt; i+1, i =&gt; i*i) .Subscribe(Console.WriteLine);var sub = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(Console.WriteLine);var sub = Observable.Interval(TimeSpan.FromSeconds(1)).Take(3).Subscribe(Console.WriteLine);Observable.Interval(TimeSpan.FromSeconds(1)).Take(3).Subscribe(Console.WriteLine, e =&gt; { }, () =&gt; Console.WriteLine(&quot;Complete&quot;));
  8. Observable.Range(0, 20).Where(x =&gt; x % 2 ==0).Subscribe(Console.WriteLine)Observable.Range(0, 20).Where(x =&gt; x % 2 ==0).Select(x =&gt; x*x).Subscribe(Console.WriteLine)Observable.Range(0, 20).Zip(Observable.Interval(TimeSpan.FromSeconds(1)), (x,y) =&gt; x).Where(x =&gt; x % 2 == 0).Subscribe(Console.WriteLine);
  9. From Blank AutoCompleteShow project structureCreate search based off property changed event handler** How would we do this with Rx?**Create propertyChanges, searchTextChanges and subscribeRun** What about blocking the UI thread?**Add doSearch, select many and subscriptionRun ** What about the exception?**ObserveOnDispatcherRun** What about too many searches?**Throttle** What about adding support for pressing enter?**TextBoxEnterCommand (Merge)** What about the duplicates?**DistinctUntilChanged** What about results coming back out of sequence?** (Temporarily remove throttle to show)TakeUntil
  10. Show codeRunIncrease throttle time