SlideShare a Scribd company logo
Reactive ExtensionsWorkshop Ryan Riley & Wes Dyer
Logistics 30 minute sections 10 minutes presentation 10 minutes coding 10 minutes discussion New partner every section Prizes for best code during each section
Where can I get them? Install with NuGet Download at MSDN Data Developer Center
Outline Introduction to Rx A Unified Programming Model The Power of Rx RxJS Schedulers Event Processing Reactive Coincidence Continuations Everywhere Programming the Cloud
introduction to rx like events but much better
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Reactive Programming In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. http://en.wikipedia.org/wiki/Reactive_programming
Why should I care? GPS RSS      feeds Stock tickers Social media UI events Server management
Reactive Programming using Events Declare eventAction<int> E; Publish E(42); Subscribe 	E += x => Console.WriteLine(x);
Reactive Programming using Rx Declare ISubject<int> S = newSubject<int>(); Publish S.OnNext(42); Subscribe S.Subscribe(x => Console.WriteLine(x));
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
classProgram { ISubject<int> S = newSubject<int>(); static void Main() { var p = newProgram(); p.S.Subscribe(x => Console.WriteLine(x)); p.S.OnNext(1); p.S.OnNext(2); p.S.OnNext(3);   } } classProgram { eventAction<int> E; static void Main() { var p = newProgram(); p.E += x => Console.WriteLine(x); p.E(1); p.E(2); p.E(3);  } } A Little Example
Separate Publish from Subscribe  Both Publish Subscribe
First-Class “Events” An object is first-class when it: can be stored in variables and data structures can be passed as a parameter to a subroutine can be returned as the result of a subroutine can be constructed at runtime has intrinsic identity (independent of any given name) http://en.wikipedia.org/wiki/First-class_object
First-Class “Events” // stored IObservable<string> textChanged = …; // passed voidProcessRequests(IObservable<string> input) {…} // returned IObservable<int> QueryServer() {…}
Punctuation classIObserver<in T> { voidOnNext(T value); voidOnError(Exception error); voidOnCompleted();}
Contract Grammar: OnNext* [OnCompleted | OnError] Serialized execution of observer’s methods 0 1 2 0 1 1 2 0 0 1 2
Challenge: Simple Transformation Implement Events.LengthChanged ImplementObservables.LengthChanged Output should be:
Answer Events Observables
Bridging from the Existing World query asynchronous data streams
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Empty // complete immediately Observable.Empty<int>();
Return // return 1 value Observable.Return(1); 1
Throw // throw an exception Observable.Throw(newException());
Never // never complete Observable.Never<int>();
Range // return three values starting with 0 Observable.Range(0, 3); 1 2 0
ToEnumerable / ToObservable // enumerable to observable Enumerable.Range(0, 3).ToObservable(); // observable to enumerable Observable.Range(0, 3).ToEnumerable(); 1 2 0
Generate // observable for loop Observable.Generate(     0,    i => i < 3,     i => i + 1,    i => i * i ); 1 4 0
Create // anything you please Observable.Create<int>(observer => { IDisposableb = newBooleanDisposable();     newThread(() =>    { for (inti = 0; i < 3&& !b.IsDisposed; ++i) observer.OnNext(i); observer.OnCompleted();         return () => {};     }).Start();     returnb; }); 1 4 0
classProgram {   static void Main() {     Labellbl = newLabel(); Formfrm = newForm {      Controls = { lbl}    }; frm.MouseMove+= (s, args) => {};   } } classProgram {   static void Main() { Labellbl = newLabel(); Formfrm = newForm {       Controls = { lbl } }; varmouseMoves= Observable .FromEventPattern<MouseEventHandler, MouseEventArgs>(        x => frm.MouseMove += x,        x => frm.MouseMove -= x); mouseMoves.Subscribe(evt => {});   } } Using Events
classProgram {   static void Main() {     Labellbl = newLabel(); Formfrm = newForm {      Controls = { lbl}    }; frm.MouseMove+= (sender, args) =>    {       if(args.Location.X== args.Location.Y)      { lbl.Text = args.Location.ToString();       }     }; Application.Run(frm);   } } classProgram {   static void Main() { Labellbl = newLabel(); Formfrm = newForm {       Controls = { lbl } }; varmouseUps = …; varmouseMoves= …; varspecificMoves =       fromup inmouseUps       frommove inmouseMoves       letlocation = move.EventArgs.Location       wherelocation.X == location.Y       selectnew { location.X, location.Y };     using(specificMoves    .Subscribe(evt => lbl.Text= evt.ToString()))     { Application.Run(frm);     }   } } LINQ to Events
Challenge Complete DictionarySuggest ,[object Object]
Create an Observable from an asynchronous web request
Combine these two observables to react to text input changes to return web service results,[object Object]
The Power of Rx taking control
Monitoring // anything you please var input = Observable     .FromEventPattern(txt, "TextChanged")     .Select(evt => ((TextBox)evt.Sender).Text)     .Timestamp()     .Do((Timestamped<string> evt) => Console.WriteLine(evt))     .Select(evt => evt.Value)     .Where(evt => evt.Length > 4)     .Do(evt => Console.WriteLine(evt));
Too Many Events
Duplication
Race Condition
Challenge Find and apply the operators to fix these issues in DictionarySuggest
Answer
JavaScript
Challenge Port DictionarySuggest to RxJS
Answer
Schedulers parameterizing concurrency
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Parameterizing Concurrency Observable.Timer(TimeSpan.FromSeconds(5)) Which timer? System.Threading.Timer? System.Timers.Timer? System.Windows.Forms.Timer? System.Windows.Threading.Timer? Sleep on the current thread? … ?
Scheduler Abstraction execution context clock execution policy
Scheduler Interface interfaceIScheduler { DateTimeOffset Now { get; } IDisposable Schedule(Action work); IDisposable Schedule(TimeSpandueTime, Action work);IDisposable Schedule(DateTimeOffsetdueTime, Action work);}
Operational Layering Operators varxs = Observable.Range(1, 10,  Scheduler.ThreadPool); var q = from x inxs where x % 2 == 0 select -x; q.Subscribe(Console.WriteLine);
Operational Layering Operators Observables varxs = newRangeObservable<int>(1, 10,  Scheduler.ThreadPool); var q = newSelectObservable<int>( newWhereObservable<int>( xs,    x => x % 2 == 0),  x => -x); q.Subscribe(   newLambdaObserver<int>(Console.WriteLine));
Operational Layering Operators Observables var n = 0; Scheduler.ThreadPool.Schedule(self => { if (n < 10) {    if ((n + 1) % 2 == 0) Console.WriteLine(-(n + 1));    n++;    self();   } }); Schedulers
Operational Layering Operators Observables var n = 0; Action<object> work = null; work = _ => { if (n < 10) {    if ((n + 1) % 2 == 0) Console.WriteLine(-(n + 1));    n++; ThreadPool.QueueUserWorkItem(null, work);  }}; ThreadPool.QueueUserWorkItem(null, work); Schedulers Native Concurrency
One Interface to Rule Them All
The Problem of Time Operations can take a long time Observable.Timer(TimeSpan.FromYears(1000))
Some operators have time-based semantics Observable.Timer(TimeSpan.FromSeconds(1))  .Buffer(TimeSpan.FromSeconds(1)) The Problem of Time 6 0 4 5 1 2 3 0 1 4 2 3 5 6 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s
When testing reactive programs, time is the problem. …virtual time is the solution. The Problem of Time
Schedulers Revisited
TestScheduler scheduler = newTestScheduler(); IObservable<string> input = scheduler.CreateObservable( OnNext(300, “wes”), OnNext(400, “ryan”), OnCompleted(500)); var results = scheduler.Run(() => input.Select(x => x.Length)); results.AssertEqual( OnNext(300, 3), OnNext(400, 4), OnCompleted(500)); Unit Testing with Schedulers
Implement MainForm.GetQuotes ImplementMainForm.GetQuery Challenge: Historical Data
Answer
event processing the power of LINQ
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Given: Stream of stock ticks Find: 10% daily price increase Event Processing
Windowing MSFT 30.73 MSFT 27.01 MSFT 27.96 INTC 21.75 MSFT 31.21 INTC 22.54 INTC 20.98 Group by symbol: GroupBy(t => t.Symbol)
Aggregation MSFT INTC 30.73 27.01 27.96 31.21 21.75 22.54 20.98 Aggregate each day with previous day: Buffer(2, 1)
Filtering MSFT INTC 31.21 30.73 27.01 27.96 27.96 31.21 21.75 22.54 22.54 20.98 Filter by price increase > 10%: Where(w => PriceIncrease(w) > .1)
Reduce MSFT INTC 27.96 31.21 Reduce to a single stream: Merge()
Done! 27.96 31.21
from tick instockTicks group tick bytick.SymbolintosymbolStream from window insymbolStream.Buffer(2, 1) let increase = PriceIncrease(window) where increase > .1 select new { symbol = symbolStream.Key, increase };  LINQ: Event Processing source group aggregate apply filter reduce
Change MainForm.Query to compute the Average High and Average Low over the past 5 trading days as well as the current Close and Date Challenge: Event Processing
Answer
Reactive coincidence streaming windows
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Event Duration 0 2 1 vs 0 2 1
An Example left  left right
Representing Duration begin begin end end Window
Store
Reactive Coincidence Which people are at the store while it is opened? 5/5 5/6 curley moe larry
Reactive Coincidence Which people are at the store while it is opened? 5/5 5/6 moe larry curley moe
LINQ Join from opening instoreOpenings join person inpersonArrives onopening.Closeequalsperson.Leavesinto g selectnew { opening.Day, People = g };
Change query in MainForm.MainForm to compute a stream of deltas when the mouse is down Challenge: Drag and Drop
Answer
Programming the cloud a glimpse into the future
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
Distributed Queries Cloud results query
Observable.Timer( TimeSpan.FromSeconds(1), Scheduler.Azure)  .ObserveLocally()  .Subscribe(Console.WriteLine); Distributed Queries Send the query to the cloud Send the results back
Pass-by-Value 	[Serializable] classMyType { … } Pass-by-Reference classMyType : MarshalByRefObject{ … } Distributed Parameters
var x = 42; scheduler.Schedule(() => Console.WriteLine(x)); classClosure { public intx; public void M() { Console.WriteLine(x);  } } var closure = newClosure(); closure.x = 42; scheduler.Schedule(closure.M); Distributed Scheduling Pass by value or reference?
interfaceIScheduler {  … IDisposable Schedule<T>(T state, Action<T> work);  … } Scheduler Interface Revisited
var x = 42; scheduler.Schedule(  x,  state => Console.WriteLine(state)); static void M(int state) { Console.WriteLine(state); } varx = 42; scheduler.Schedule(  x,  M); Distributed Scheduling No closures!!!
scheduler.Schedule(42, x => scheduler.Schedule(x + 1, y => Console.WriteLine(y))); Nested Scheduling
Distributed Scheduling cloud Scheduler
interfaceIScheduler {  … IDisposable Schedule<T>(T state,    Action<IScheduler, T> work);  … } Scheduler Interface Rerevisited
scheduler.Schedule(42, (s, x) => s.Schedule(x + 1, y => Console.WriteLine(y))); Nested Scheduling
Fan-out Scheduling Scheduler Scheduler Scheduler Scheduler Scheduler Scheduler Scheduler
var d = scheduler.Schedule(42, (s, x) => { var d1 = s.Schedule(x + 1, Console.WriteLine); var d2 = s.Schedule(x + 2, Console.WriteLine); }); Fan-out Scheduling How do we make d depend on d1 & d2?
interfaceIScheduler {  … IDisposable Schedule<T>(T state, Func<IScheduler, T, IDisposable> work);  … } Scheduler Interface Rererevisited
var d = scheduler.Schedule(42, (s, x) => { var d1 = s.Schedule(x + 1, Console.WriteLine); vard2 = s.Schedule(x + 2, Console.WriteLine);   return newCompositeDisposable(d1, d2); }); Fan-out Scheduling
scheduler.Schedule(42, (state, self) =>  { Console.WriteLine(state);    self(state + 1);  }); Easy Recursive Scheduling
Change Program.Main to use the AppDomainScheduler ReimplementGenerateObservable.Subscribe Challenge: AppDomains
Answer
Continuations Everywhere continuation-passing style used elsewhere
Ruby 1..10.each do |x|    puts x * xend
AJAX $.ajax({ 	url: 'http://en.wikipedia.org/w/api.php', dataType: 'jsonp', data: { 		action: 'opensearch', 		search: term, 		format: 'json' 	}, success: function(msg) { 	alert('Data saved:' + msg); } });
node.js var net = require('net'); var server = net.createServer(function (socket) { socket.write("Echo server"); 	socket.pipe(socket); }); server.listen(1337, "127.0.0.1");
Challenge Using Rx, build a TCP server that works in a similar manner to node.js.
The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers

More Related Content

What's hot

Teaching F#
Teaching F#Teaching F#
Teaching F#
Tomas Petricek
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
Scott Wlaschin
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
IoT Code Lab
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
Eelco Visser
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
Ali Aminian
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functionsvinay arora
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Himanshu Kaushik
 

What's hot (20)

Teaching F#
Teaching F#Teaching F#
Teaching F#
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Function C++
Function C++ Function C++
Function C++
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 

Viewers also liked

Types Of Ecosystems
Types Of EcosystemsTypes Of Ecosystems
Types Of EcosystemsUTS
 
Introduction to F#x
Introduction to F#xIntroduction to F#x
Introduction to F#x
Ryan Riley
 
The Functional Web
The Functional WebThe Functional Web
The Functional Web
Ryan Riley
 
HTTP: the Other ESB
HTTP: the Other ESBHTTP: the Other ESB
HTTP: the Other ESB
Ryan Riley
 
Os utopistas thommaso campanella
Os utopistas thommaso campanellaOs utopistas thommaso campanella
Os utopistas thommaso campanellaJorge Miklos
 
Os utopistas thomas more
Os utopistas thomas moreOs utopistas thomas more
Os utopistas thomas moreJorge Miklos
 

Viewers also liked (7)

Types Of Ecosystems
Types Of EcosystemsTypes Of Ecosystems
Types Of Ecosystems
 
Introduction to F#x
Introduction to F#xIntroduction to F#x
Introduction to F#x
 
The Functional Web
The Functional WebThe Functional Web
The Functional Web
 
HTTP: the Other ESB
HTTP: the Other ESBHTTP: the Other ESB
HTTP: the Other ESB
 
Test first
Test firstTest first
Test first
 
Os utopistas thommaso campanella
Os utopistas thommaso campanellaOs utopistas thommaso campanella
Os utopistas thommaso campanella
 
Os utopistas thomas more
Os utopistas thomas moreOs utopistas thomas more
Os utopistas thomas more
 

Similar to Rx workshop

Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
Dustin Graham
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smetnkaluva
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
Shahar Barsheshet
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014
hezamu
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Florent Pillet
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
Mahmoud Samir Fayed
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
EPAM
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 

Similar to Rx workshop (20)

Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smet
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 

Recently uploaded

Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 

Recently uploaded (20)

Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 

Rx workshop

  • 2. Logistics 30 minute sections 10 minutes presentation 10 minutes coding 10 minutes discussion New partner every section Prizes for best code during each section
  • 3. Where can I get them? Install with NuGet Download at MSDN Data Developer Center
  • 4. Outline Introduction to Rx A Unified Programming Model The Power of Rx RxJS Schedulers Event Processing Reactive Coincidence Continuations Everywhere Programming the Cloud
  • 5. introduction to rx like events but much better
  • 6. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 7. Reactive Programming In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. http://en.wikipedia.org/wiki/Reactive_programming
  • 8. Why should I care? GPS RSS feeds Stock tickers Social media UI events Server management
  • 9. Reactive Programming using Events Declare eventAction<int> E; Publish E(42); Subscribe E += x => Console.WriteLine(x);
  • 10. Reactive Programming using Rx Declare ISubject<int> S = newSubject<int>(); Publish S.OnNext(42); Subscribe S.Subscribe(x => Console.WriteLine(x));
  • 11. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 12. classProgram { ISubject<int> S = newSubject<int>(); static void Main() { var p = newProgram(); p.S.Subscribe(x => Console.WriteLine(x)); p.S.OnNext(1); p.S.OnNext(2); p.S.OnNext(3); } } classProgram { eventAction<int> E; static void Main() { var p = newProgram(); p.E += x => Console.WriteLine(x); p.E(1); p.E(2); p.E(3); } } A Little Example
  • 13. Separate Publish from Subscribe Both Publish Subscribe
  • 14. First-Class “Events” An object is first-class when it: can be stored in variables and data structures can be passed as a parameter to a subroutine can be returned as the result of a subroutine can be constructed at runtime has intrinsic identity (independent of any given name) http://en.wikipedia.org/wiki/First-class_object
  • 15. First-Class “Events” // stored IObservable<string> textChanged = …; // passed voidProcessRequests(IObservable<string> input) {…} // returned IObservable<int> QueryServer() {…}
  • 16. Punctuation classIObserver<in T> { voidOnNext(T value); voidOnError(Exception error); voidOnCompleted();}
  • 17. Contract Grammar: OnNext* [OnCompleted | OnError] Serialized execution of observer’s methods 0 1 2 0 1 1 2 0 0 1 2
  • 18. Challenge: Simple Transformation Implement Events.LengthChanged ImplementObservables.LengthChanged Output should be:
  • 20. Bridging from the Existing World query asynchronous data streams
  • 21. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 22. Empty // complete immediately Observable.Empty<int>();
  • 23. Return // return 1 value Observable.Return(1); 1
  • 24. Throw // throw an exception Observable.Throw(newException());
  • 25. Never // never complete Observable.Never<int>();
  • 26. Range // return three values starting with 0 Observable.Range(0, 3); 1 2 0
  • 27. ToEnumerable / ToObservable // enumerable to observable Enumerable.Range(0, 3).ToObservable(); // observable to enumerable Observable.Range(0, 3).ToEnumerable(); 1 2 0
  • 28. Generate // observable for loop Observable.Generate( 0, i => i < 3, i => i + 1, i => i * i ); 1 4 0
  • 29. Create // anything you please Observable.Create<int>(observer => { IDisposableb = newBooleanDisposable(); newThread(() => { for (inti = 0; i < 3&& !b.IsDisposed; ++i) observer.OnNext(i); observer.OnCompleted(); return () => {}; }).Start(); returnb; }); 1 4 0
  • 30. classProgram { static void Main() { Labellbl = newLabel(); Formfrm = newForm { Controls = { lbl} }; frm.MouseMove+= (s, args) => {}; } } classProgram { static void Main() { Labellbl = newLabel(); Formfrm = newForm { Controls = { lbl } }; varmouseMoves= Observable .FromEventPattern<MouseEventHandler, MouseEventArgs>( x => frm.MouseMove += x, x => frm.MouseMove -= x); mouseMoves.Subscribe(evt => {}); } } Using Events
  • 31. classProgram { static void Main() { Labellbl = newLabel(); Formfrm = newForm { Controls = { lbl} }; frm.MouseMove+= (sender, args) => { if(args.Location.X== args.Location.Y) { lbl.Text = args.Location.ToString(); } }; Application.Run(frm); } } classProgram { static void Main() { Labellbl = newLabel(); Formfrm = newForm { Controls = { lbl } }; varmouseUps = …; varmouseMoves= …; varspecificMoves = fromup inmouseUps frommove inmouseMoves letlocation = move.EventArgs.Location wherelocation.X == location.Y selectnew { location.X, location.Y }; using(specificMoves .Subscribe(evt => lbl.Text= evt.ToString())) { Application.Run(frm); } } } LINQ to Events
  • 32.
  • 33. Create an Observable from an asynchronous web request
  • 34.
  • 35. The Power of Rx taking control
  • 36. Monitoring // anything you please var input = Observable .FromEventPattern(txt, "TextChanged") .Select(evt => ((TextBox)evt.Sender).Text) .Timestamp() .Do((Timestamped<string> evt) => Console.WriteLine(evt)) .Select(evt => evt.Value) .Where(evt => evt.Length > 4) .Do(evt => Console.WriteLine(evt));
  • 40. Challenge Find and apply the operators to fix these issues in DictionarySuggest
  • 46. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 47. Parameterizing Concurrency Observable.Timer(TimeSpan.FromSeconds(5)) Which timer? System.Threading.Timer? System.Timers.Timer? System.Windows.Forms.Timer? System.Windows.Threading.Timer? Sleep on the current thread? … ?
  • 48. Scheduler Abstraction execution context clock execution policy
  • 49. Scheduler Interface interfaceIScheduler { DateTimeOffset Now { get; } IDisposable Schedule(Action work); IDisposable Schedule(TimeSpandueTime, Action work);IDisposable Schedule(DateTimeOffsetdueTime, Action work);}
  • 50. Operational Layering Operators varxs = Observable.Range(1, 10, Scheduler.ThreadPool); var q = from x inxs where x % 2 == 0 select -x; q.Subscribe(Console.WriteLine);
  • 51. Operational Layering Operators Observables varxs = newRangeObservable<int>(1, 10, Scheduler.ThreadPool); var q = newSelectObservable<int>( newWhereObservable<int>( xs, x => x % 2 == 0), x => -x); q.Subscribe( newLambdaObserver<int>(Console.WriteLine));
  • 52. Operational Layering Operators Observables var n = 0; Scheduler.ThreadPool.Schedule(self => { if (n < 10) { if ((n + 1) % 2 == 0) Console.WriteLine(-(n + 1)); n++; self(); } }); Schedulers
  • 53. Operational Layering Operators Observables var n = 0; Action<object> work = null; work = _ => { if (n < 10) { if ((n + 1) % 2 == 0) Console.WriteLine(-(n + 1)); n++; ThreadPool.QueueUserWorkItem(null, work); }}; ThreadPool.QueueUserWorkItem(null, work); Schedulers Native Concurrency
  • 54. One Interface to Rule Them All
  • 55. The Problem of Time Operations can take a long time Observable.Timer(TimeSpan.FromYears(1000))
  • 56. Some operators have time-based semantics Observable.Timer(TimeSpan.FromSeconds(1)) .Buffer(TimeSpan.FromSeconds(1)) The Problem of Time 6 0 4 5 1 2 3 0 1 4 2 3 5 6 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s 1s
  • 57. When testing reactive programs, time is the problem. …virtual time is the solution. The Problem of Time
  • 59. TestScheduler scheduler = newTestScheduler(); IObservable<string> input = scheduler.CreateObservable( OnNext(300, “wes”), OnNext(400, “ryan”), OnCompleted(500)); var results = scheduler.Run(() => input.Select(x => x.Length)); results.AssertEqual( OnNext(300, 3), OnNext(400, 4), OnCompleted(500)); Unit Testing with Schedulers
  • 62. event processing the power of LINQ
  • 63. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 64. Given: Stream of stock ticks Find: 10% daily price increase Event Processing
  • 65. Windowing MSFT 30.73 MSFT 27.01 MSFT 27.96 INTC 21.75 MSFT 31.21 INTC 22.54 INTC 20.98 Group by symbol: GroupBy(t => t.Symbol)
  • 66. Aggregation MSFT INTC 30.73 27.01 27.96 31.21 21.75 22.54 20.98 Aggregate each day with previous day: Buffer(2, 1)
  • 67. Filtering MSFT INTC 31.21 30.73 27.01 27.96 27.96 31.21 21.75 22.54 22.54 20.98 Filter by price increase > 10%: Where(w => PriceIncrease(w) > .1)
  • 68. Reduce MSFT INTC 27.96 31.21 Reduce to a single stream: Merge()
  • 70. from tick instockTicks group tick bytick.SymbolintosymbolStream from window insymbolStream.Buffer(2, 1) let increase = PriceIncrease(window) where increase > .1 select new { symbol = symbolStream.Key, increase }; LINQ: Event Processing source group aggregate apply filter reduce
  • 71. Change MainForm.Query to compute the Average High and Average Low over the past 5 trading days as well as the current Close and Date Challenge: Event Processing
  • 74. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 75. Event Duration 0 2 1 vs 0 2 1
  • 76. An Example left left right
  • 77. Representing Duration begin begin end end Window
  • 78. Store
  • 79. Reactive Coincidence Which people are at the store while it is opened? 5/5 5/6 curley moe larry
  • 80. Reactive Coincidence Which people are at the store while it is opened? 5/5 5/6 moe larry curley moe
  • 81. LINQ Join from opening instoreOpenings join person inpersonArrives onopening.Closeequalsperson.Leavesinto g selectnew { opening.Day, People = g };
  • 82. Change query in MainForm.MainForm to compute a stream of deltas when the mouse is down Challenge: Drag and Drop
  • 84. Programming the cloud a glimpse into the future
  • 85. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 86. Distributed Queries Cloud results query
  • 87. Observable.Timer( TimeSpan.FromSeconds(1), Scheduler.Azure) .ObserveLocally() .Subscribe(Console.WriteLine); Distributed Queries Send the query to the cloud Send the results back
  • 88. Pass-by-Value [Serializable] classMyType { … } Pass-by-Reference classMyType : MarshalByRefObject{ … } Distributed Parameters
  • 89. var x = 42; scheduler.Schedule(() => Console.WriteLine(x)); classClosure { public intx; public void M() { Console.WriteLine(x); } } var closure = newClosure(); closure.x = 42; scheduler.Schedule(closure.M); Distributed Scheduling Pass by value or reference?
  • 90. interfaceIScheduler { … IDisposable Schedule<T>(T state, Action<T> work); … } Scheduler Interface Revisited
  • 91. var x = 42; scheduler.Schedule( x, state => Console.WriteLine(state)); static void M(int state) { Console.WriteLine(state); } varx = 42; scheduler.Schedule( x, M); Distributed Scheduling No closures!!!
  • 92. scheduler.Schedule(42, x => scheduler.Schedule(x + 1, y => Console.WriteLine(y))); Nested Scheduling
  • 94. interfaceIScheduler { … IDisposable Schedule<T>(T state, Action<IScheduler, T> work); … } Scheduler Interface Rerevisited
  • 95. scheduler.Schedule(42, (s, x) => s.Schedule(x + 1, y => Console.WriteLine(y))); Nested Scheduling
  • 96. Fan-out Scheduling Scheduler Scheduler Scheduler Scheduler Scheduler Scheduler Scheduler
  • 97. var d = scheduler.Schedule(42, (s, x) => { var d1 = s.Schedule(x + 1, Console.WriteLine); var d2 = s.Schedule(x + 2, Console.WriteLine); }); Fan-out Scheduling How do we make d depend on d1 & d2?
  • 98. interfaceIScheduler { … IDisposable Schedule<T>(T state, Func<IScheduler, T, IDisposable> work); … } Scheduler Interface Rererevisited
  • 99. var d = scheduler.Schedule(42, (s, x) => { var d1 = s.Schedule(x + 1, Console.WriteLine); vard2 = s.Schedule(x + 2, Console.WriteLine); return newCompositeDisposable(d1, d2); }); Fan-out Scheduling
  • 100. scheduler.Schedule(42, (state, self) => { Console.WriteLine(state); self(state + 1); }); Easy Recursive Scheduling
  • 101. Change Program.Main to use the AppDomainScheduler ReimplementGenerateObservable.Subscribe Challenge: AppDomains
  • 102. Answer
  • 104. Ruby 1..10.each do |x| puts x * xend
  • 105. AJAX $.ajax({ url: 'http://en.wikipedia.org/w/api.php', dataType: 'jsonp', data: { action: 'opensearch', search: term, format: 'json' }, success: function(msg) { alert('Data saved:' + msg); } });
  • 106. node.js var net = require('net'); var server = net.createServer(function (socket) { socket.write("Echo server"); socket.pipe(socket); }); server.listen(1337, "127.0.0.1");
  • 107. Challenge Using Rx, build a TCP server that works in a similar manner to node.js.
  • 108. The Reactive Extensions Rx is … a set of types representing asynchronous data streams a set of operators to query asynchronous data streams a set of types to parameterize concurrency Rx = Observables + LINQ + Schedulers
  • 109. Learn More Resources Rx Developer Center Rx on Channel 9 Projects ReactiveUI Fluent State Observer Reactive ETL ReactiveOAuth Reactive Remoting Extensions to the Extensions Reactive Extensions – Extensions Rx Contrib RxUtilities Rx Power Toys

Editor's Notes

  1. Guaranteed sequential or
  2. Does the code correctly add/remove multiple handlers?Is the code thread-safe?Can the code be refactored into a method?Can the code be generalized?
  3. Discuss: Using Rx for web clients – same library with an Rx prefix, library integrationDemo: run through demos from the Bridging from the Existing World sectionDemo: jQuery integrationImage from http://www.skorks.com/wp-content/uploads/2010/04/javascript.jpg
  4. How did you create an observablein GetQuotes?Did GetQuotes have any specific knowledge of what type of scheduler it uses?Did Query have any specific knowledge of how the observable it uses was produced?Why can we return IObservable&lt;object&gt; from Query?What does MyHistoricalScheduler.Run do?Ext.BindToChart contains an operator called ObserveOn, what does this do? What happens if we remove it?
  5. Were you able to reuse most of your previous code?Could you create more complex queries from the results of your new query?What would you do if you wanted to capture the last 5 days and not the last 5 trading days?What really is the power of LINQ?
  6. Which event has a duration?Which event stream defines the windows?Which event stream defines the data?Can an event stream without duration define the windows?Given a stream of points how can we compute deltas?Did you consider the initial point where the mouse button was clicked?
  7. What are the two basic parameter passing mechanisms in distributed systems? How are they indicated?Why don’t closures work in distributed systems?Regarding the scheduler interface…Why is the state passed in?Why is a disposable returned by the func?Why is there a scheduler argument in the func?
  8. Demo: jQuery.ajax function with callbacks