SlideShare a Scribd company logo
1 of 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

More Related Content

Similar to Introduction to Reactive Extensions

Reactive Extensions, Rx
Reactive Extensions, RxReactive Extensions, Rx
Reactive Extensions, RxDima Pasko
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive ExtensionsKiev ALT.NET
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架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
 
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
 

Similar to Introduction to Reactive Extensions (20)

Reactive Extensions, Rx
Reactive Extensions, RxReactive Extensions, Rx
Reactive Extensions, Rx
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
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
 
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
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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

Editor's Notes

  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