SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Dernier (20)

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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL 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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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

Notes de l'éditeur

  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