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




Peter Goodman

An Introduction to Reactive
Extensions
2
                    Introduction to Reactive Extensions




What are Reactive Extensions?
3
                    Introduction to Reactive Extensions




What are Reactive Extensions?
4
                    Introduction to Reactive Extensions




What are Reactive Extensions?
5
                    Introduction to Reactive Extensions




What are Reactive Extensions?
6
                                     Introduction to Reactive Extensions



Events in .Net

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

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




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



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

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


What if events were collections?
  Collection




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


  Event Stream


                                                                                            TIME


OnNext      OnNext      OnNext      OnNext      OnNext         OnNext
9
                                    Introduction to Reactive Extensions


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

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

              Summary Push vs Pull
                                       Application
Interactive




                           MoveNext




                                                                                                         Reactive
               Got next?




                                                          OnNext
                                                                              Have next!



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



                                      Environment
11
                                    Introduction to Reactive Extensions


Creating Observables - Primitive
                  OnCompleted
            .Empty<int>()                new int[0]

                    OnNext
            .Return(42)                   new[] { 42 }


                          OnError
            .Throw<int>(ex)               Throwing iterator


            .Never<int>()
                                         Iterator that got stuck
 Notion of time
12
                                Introduction to Reactive Extensions




Creating Observables - Range

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



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


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

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

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



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

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




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



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


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

           select                      .Location

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




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



Introducing Asynchrony

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

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


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




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

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




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




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




DEMO
Synchronization
22
                                 Introduction to Reactive Extensions



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




DEMO
Rx for JavaScript
24
                      Introduction to Reactive Extensions




Reactive Extensions

Questions?
25
                                  Introduction to Reactive Extensions




Resources
 MSDN

 Bart de Smet / Rx (Channel 9)

 Reactive UI

 Pushqa / SignalR
26
                            Introduction to Reactive Extensions




Contact
 pete@petegoo.com

 http://blog.petegoo.com

 Twitter: @petegoo

Más contenido relacionado

Similar a Introduction to Reactive Extensions

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

Similar a Introduction to Reactive Extensions (20)

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

Último

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
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
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Último (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
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.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

Introduction to Reactive Extensions

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

Notas del editor

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