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

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
 

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

Dernier

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 

Dernier (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 

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