SlideShare uma empresa Scribd logo
1 de 30
Reactive Programming with F# Tomáš Petříček Microsoft C# MVP http://tomasp.net/blog
A little bit about me… Real-World Functional Programming with Jon Skeet Today’s talk based on some ideas from Chapter 16 Worked on F# at MSR Internships with Don Syme Web programming and reactive programming in F# Some Visual Studio 2010 IntelliSense
What is this talk about? It is not about concurrent programming Multiple threads, various programming models Immutable data using Tasks or Parallel LINQ We have full control over the control flow Message passing using F# MailboxProcessor Processors react to received messages  It is about reactive programming Components that react to events in general MailboxProcessoris one possible implementation Can be single-threaded – running on GUI thread
Single-threaded reactive programming Single-threading makes GUI simple (possible!) Reactive part of the application reacts quickly Expensive work should be done in background Declarative – what to do with received data  Define data-flow using event combinators      ⊕Simple & elegant   ⊝Limited expressivity Imperative – how to react to received data Define control-flow using asynchronous workflows  ⊝Write more code   ⊕Easy for difficult tasks
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Everybody loves declarative style!  Used by numerous .NET libraries  LINQ for specifying queries in C# Specifying layout of user interface in WPF/Silverlight Can be used for specifying reactive aspects too! Declarative <Button Content="Click me!"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:CallMethodAction MethodName="Process"(...)/> </i:EventTrigger> </i:Interaction.Triggers> </Button> Triggered when this event occurs This action calls specified method
Everybody loves declarative style!  (2.) Specifying more complex behaviors We can write new Triggers and Actions… For example Silverlight Experimental Hacks Library We can specify conditions for triggers Triggered only when chkAllow.Enabled == true <Button Content="Click me!"><i:Interaction.Triggers> <ex:EventTriggerEventName="Click"> <ex:EventTrigger.Conditions><ex:InvokingConditions> <ex:InvokingConditionElementName="chkAllow"          Property="Enabled" Value="True" /> </ex:InvokingConditions></ex:EventTrigger.Conditions> <ex:PropertyActionPropertyName="Visible"Value="True"/> </ex:EventTrigger> </i:Interaction.Triggers></Button> Displays some control
Digression: Declarative list processing Essentially the same thing as LINQ queries  Declarative – specify what results we want  Create list of points >letpoints= [ (0.0, 50.0); (100.0, 0.0); (300.0, 100.0) ]   ;; >List.map(fun (x, y) ->x+25.0, y+25.0) points ;; val it : (float * float) list =  [(25.0, 75.0); (125.0, 25.0); (325.0, 125.0)] >points |>List.map (fun (x, y) ->x+25.0, y+25.0) |>List.filter (fun (x, y) ->x<200.0&&y<100.0) |>List.iter (fun (x, y) ->printf"[%f, %f] "xy)  ;; [25.000000, 75.000000] [125.000000, 25.000000] Add 25 to X and Y coordinates * First add 25 * Limit range * Print points
DEMO Introducing F# event combinators
Digression: Dynamic invoke in F# Access members not known at compile-time Simple version of dynamic keyword in C# We can easily define behavior of the operator How does it work?  When we write… …the compiler treats it as: let (?) (this:Control) (prop:string) :'T= this.FindName(prop) :?>'T letball :Ellipse = this?Ball let ball :Ellipse = (?) this "Ball"
More about F# events Events in F# are first-class values Implement interface type IEvent<'T> Events carry values 'Tsuch as MouseEventArgs Can be passed as arguments, returned as results We use functions for working with event values Create new event that carries different type of value and is triggered only in some cases Event.add registers handler to the final event Event.map   : ('T -> 'R)   -> IEvent<'T> -> IEvent<'R> Event.filter : ('T -> bool) -> IEvent<'T> -> IEvent<'T>
Two interesting event combinators Merging events with Event.merge Triggered whenever first or second event occurs Note that the carried values must have same type Creating stateful events with Event.scan State is recalculated each time event occurs Triggered with new state after recalculation IEvent<'T> -> IEvent<'T> -> IEvent<'T> ('St -> 'T -> 'St) -> 'St -> IEvent<'T> -> IEvent<'St>
Creating ColorSelector control Three sliders for changing color components Box shows current color Data-flow diagram describes the activity Diagrams
DEMO Writing ColorSelector control with F# events
Accessing F# events from C# Events in F# are values of type IEvent<'T> Enables F# way of working with events Attribute instructs F# to generate .NET event IEvent<'T> vs. IObservable<'T> in .NET 4.0 You can work with both of them from F# Using combinators such as Observable.mapetc. Observable keeps separate state for each handler Can be confusing if you add/remove handlers  [<CLIEvent>] memberx.ColorChanged=colorChanged
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Creating SemaphoreLight control Typical approach – store state as int or enum Imperative code uses mutable fields With event combinators, we use Event.scan Difficult to read – what does state represent? It is hard to see what the transitions are! Better approach – write workflow that loops between states (points in code) Asynchronous waiting on events causes transitions Diagrams
DEMO Writing SemaphoreLight with workflows
Workflows for GUI programming Async.AwaitObservableoperation Creates workflow that waits for the first occurrence Currently not part of F# libraries / PowerPack Sometimes, using IObservable<'T> is better Works because IEvent<'T> : IObservable<'T> Async.StartImmediateoperation Starts the workflow on the current (e.g. GUI) thread Callbacks always return to original kind of thread All code in the demo runs on GUI thread as required! AwaitObservable : IObservable<'T> -> Async<'T>
Writing loops using workflows Using looping constructs like whileand for Functional style – using recursion letsemaphoreStates2() =async { whiletruedo forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) } “Infinite” loop letrecsemaphoreStates() =async { forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current)  do!semaphoreStates() } Recursive call written using “do!”
Break: Time for a bit of Art…
Application for drawing rectangles Choosing between multiple transitions? AwaitObservable taking two events  Resume when the first event fires complexdiagrams
DEMO Drawing rectangles in Silverlight
Waiting for multiple events Choosing between two (or more) events Specify two different transitions from single state Overloads for more events available too AwaitObservable: IObservable<'T> * IObservable<'U>  -> Async<Choice<'T, 'U>> Overload taking two events as parameters let!evt=Async.AwaitObservable (main.MouseLeftButtonDown, main.MouseMove) matchevtwith | Choice1Of2(up) -> // Left button was clicked | Choice2Of2(move) -> // Mouse cursor moved } Returns Choice<'T1,'T2>
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Patterns for asynchronous programming Begin/End pattern used by standard libraries Event-based pattern used more recently Can we write this using AwaitObservable? Little tricky – need to attach handler first! lethr=HttpWebRequest.Create("http://...") let!resp=hr.AsyncGetResponse() letsr=resp.GetResponseStream() Created from  Begin/EndGetResponse letwc=newWebClient() wc.DownloadStringCompleted.Add(funres-> letstring=res.Result ) wc.DownloadStringAsync("http://...") Register handler and then start
Performing asynchronous calls correctly Introducing GuardedAwaitObservableprimitive Calls a function after attaching event handler We cannot accidentally lose event occurrence  Mixing asynchronous I/O and GUI code If started from GUI thread, will return to GUI thread We can safely access controls after HTTP request async { letwc=newWebClient() let!res= Async.GuardedAwaitObservablewc.DownloadStringCompleted (fun () ->wc.DownloadStringAsync(newUri(uri)))   // (...) }
DEMO Social rectangle drawing application web 2.0 inside!!
Brief summary of the talk Reactive code can run on the GUI thread! Two programming styles in F# Declarative or data-flow style Using Event.scan combinators Imperative or control-flow style Using AwaitEvent primitive In both cases, we can use diagrams Web requests from workflows Both common patterns work
Thanks! Questions?

Mais conteúdo relacionado

Mais procurados

Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 
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
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
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 3Philip Schwarz
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014Phillip Trelford
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)IoT Code Lab
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & ImportMohd Sajjad
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusDhivyaSubramaniyam
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 

Mais procurados (20)

Teaching F#
Teaching F#Teaching F#
Teaching F#
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
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)
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
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
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 

Destaque

RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUIRESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUIBiblioteca_Drept
 
Eunis federation2
Eunis federation2Eunis federation2
Eunis federation2HEAnet
 
Configuring and managing a red
Configuring and managing a redConfiguring and managing a red
Configuring and managing a redzied01
 
Registrul Matricol Unic Documentatia De Atribuire
Registrul Matricol Unic   Documentatia De AtribuireRegistrul Matricol Unic   Documentatia De Atribuire
Registrul Matricol Unic Documentatia De Atribuiredstanca
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaAlexandre Morgaut
 
The Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please EveryoneThe Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please EveryoneIulian Dogariu
 

Destaque (8)

RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUIRESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
 
Eunis federation2
Eunis federation2Eunis federation2
Eunis federation2
 
Configuring and managing a red
Configuring and managing a redConfiguring and managing a red
Configuring and managing a red
 
Scala
ScalaScala
Scala
 
Registrul Matricol Unic Documentatia De Atribuire
Registrul Matricol Unic   Documentatia De AtribuireRegistrul Matricol Unic   Documentatia De Atribuire
Registrul Matricol Unic Documentatia De Atribuire
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with Wakanda
 
The Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please EveryoneThe Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please Everyone
 
Firebird meets NoSQL
Firebird meets NoSQLFirebird meets NoSQL
Firebird meets NoSQL
 

Semelhante a Reactive fsharp

Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Igor Moochnick
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
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) Datagreenwop
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersKris Verlaenen
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSFSoftServe
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflowsmdlm
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksRandy Connolly
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementationdavejohnson
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Jonas Follesø
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya Patsovska
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
Building real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org PlatformBuilding real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org PlatformJaveline B.V.
 

Semelhante a Reactive fsharp (20)

Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
 
Intro to RX
Intro to RXIntro to RX
Intro to RX
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Event
EventEvent
Event
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
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
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developers
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflows
 
ReactJS
ReactJSReactJS
ReactJS
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementation
 
WPF Controls
WPF ControlsWPF Controls
WPF Controls
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Building real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org PlatformBuilding real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org Platform
 

Mais de Skills Matter

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard LawrenceSkills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimSkills Matter
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Skills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlSkills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsSkills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Skills Matter
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Skills Matter
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldSkills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Skills Matter
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Skills Matter
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingSkills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveSkills Matter
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tSkills Matter
 

Mais de Skills Matter (20)

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 

Último

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Reactive fsharp

  • 1. Reactive Programming with F# Tomáš Petříček Microsoft C# MVP http://tomasp.net/blog
  • 2. A little bit about me… Real-World Functional Programming with Jon Skeet Today’s talk based on some ideas from Chapter 16 Worked on F# at MSR Internships with Don Syme Web programming and reactive programming in F# Some Visual Studio 2010 IntelliSense
  • 3. What is this talk about? It is not about concurrent programming Multiple threads, various programming models Immutable data using Tasks or Parallel LINQ We have full control over the control flow Message passing using F# MailboxProcessor Processors react to received messages It is about reactive programming Components that react to events in general MailboxProcessoris one possible implementation Can be single-threaded – running on GUI thread
  • 4. Single-threaded reactive programming Single-threading makes GUI simple (possible!) Reactive part of the application reacts quickly Expensive work should be done in background Declarative – what to do with received data Define data-flow using event combinators ⊕Simple & elegant ⊝Limited expressivity Imperative – how to react to received data Define control-flow using asynchronous workflows ⊝Write more code ⊕Easy for difficult tasks
  • 5. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 6. Everybody loves declarative style! Used by numerous .NET libraries LINQ for specifying queries in C# Specifying layout of user interface in WPF/Silverlight Can be used for specifying reactive aspects too! Declarative <Button Content="Click me!"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:CallMethodAction MethodName="Process"(...)/> </i:EventTrigger> </i:Interaction.Triggers> </Button> Triggered when this event occurs This action calls specified method
  • 7. Everybody loves declarative style! (2.) Specifying more complex behaviors We can write new Triggers and Actions… For example Silverlight Experimental Hacks Library We can specify conditions for triggers Triggered only when chkAllow.Enabled == true <Button Content="Click me!"><i:Interaction.Triggers> <ex:EventTriggerEventName="Click"> <ex:EventTrigger.Conditions><ex:InvokingConditions> <ex:InvokingConditionElementName="chkAllow" Property="Enabled" Value="True" /> </ex:InvokingConditions></ex:EventTrigger.Conditions> <ex:PropertyActionPropertyName="Visible"Value="True"/> </ex:EventTrigger> </i:Interaction.Triggers></Button> Displays some control
  • 8. Digression: Declarative list processing Essentially the same thing as LINQ queries Declarative – specify what results we want Create list of points >letpoints= [ (0.0, 50.0); (100.0, 0.0); (300.0, 100.0) ] ;; >List.map(fun (x, y) ->x+25.0, y+25.0) points ;; val it : (float * float) list = [(25.0, 75.0); (125.0, 25.0); (325.0, 125.0)] >points |>List.map (fun (x, y) ->x+25.0, y+25.0) |>List.filter (fun (x, y) ->x<200.0&&y<100.0) |>List.iter (fun (x, y) ->printf"[%f, %f] "xy) ;; [25.000000, 75.000000] [125.000000, 25.000000] Add 25 to X and Y coordinates * First add 25 * Limit range * Print points
  • 9. DEMO Introducing F# event combinators
  • 10. Digression: Dynamic invoke in F# Access members not known at compile-time Simple version of dynamic keyword in C# We can easily define behavior of the operator How does it work? When we write… …the compiler treats it as: let (?) (this:Control) (prop:string) :'T= this.FindName(prop) :?>'T letball :Ellipse = this?Ball let ball :Ellipse = (?) this "Ball"
  • 11. More about F# events Events in F# are first-class values Implement interface type IEvent<'T> Events carry values 'Tsuch as MouseEventArgs Can be passed as arguments, returned as results We use functions for working with event values Create new event that carries different type of value and is triggered only in some cases Event.add registers handler to the final event Event.map : ('T -> 'R) -> IEvent<'T> -> IEvent<'R> Event.filter : ('T -> bool) -> IEvent<'T> -> IEvent<'T>
  • 12. Two interesting event combinators Merging events with Event.merge Triggered whenever first or second event occurs Note that the carried values must have same type Creating stateful events with Event.scan State is recalculated each time event occurs Triggered with new state after recalculation IEvent<'T> -> IEvent<'T> -> IEvent<'T> ('St -> 'T -> 'St) -> 'St -> IEvent<'T> -> IEvent<'St>
  • 13. Creating ColorSelector control Three sliders for changing color components Box shows current color Data-flow diagram describes the activity Diagrams
  • 14. DEMO Writing ColorSelector control with F# events
  • 15. Accessing F# events from C# Events in F# are values of type IEvent<'T> Enables F# way of working with events Attribute instructs F# to generate .NET event IEvent<'T> vs. IObservable<'T> in .NET 4.0 You can work with both of them from F# Using combinators such as Observable.mapetc. Observable keeps separate state for each handler Can be confusing if you add/remove handlers [<CLIEvent>] memberx.ColorChanged=colorChanged
  • 16. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 17. Creating SemaphoreLight control Typical approach – store state as int or enum Imperative code uses mutable fields With event combinators, we use Event.scan Difficult to read – what does state represent? It is hard to see what the transitions are! Better approach – write workflow that loops between states (points in code) Asynchronous waiting on events causes transitions Diagrams
  • 18. DEMO Writing SemaphoreLight with workflows
  • 19. Workflows for GUI programming Async.AwaitObservableoperation Creates workflow that waits for the first occurrence Currently not part of F# libraries / PowerPack Sometimes, using IObservable<'T> is better Works because IEvent<'T> : IObservable<'T> Async.StartImmediateoperation Starts the workflow on the current (e.g. GUI) thread Callbacks always return to original kind of thread All code in the demo runs on GUI thread as required! AwaitObservable : IObservable<'T> -> Async<'T>
  • 20. Writing loops using workflows Using looping constructs like whileand for Functional style – using recursion letsemaphoreStates2() =async { whiletruedo forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) } “Infinite” loop letrecsemaphoreStates() =async { forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) do!semaphoreStates() } Recursive call written using “do!”
  • 21. Break: Time for a bit of Art…
  • 22. Application for drawing rectangles Choosing between multiple transitions? AwaitObservable taking two events Resume when the first event fires complexdiagrams
  • 23. DEMO Drawing rectangles in Silverlight
  • 24. Waiting for multiple events Choosing between two (or more) events Specify two different transitions from single state Overloads for more events available too AwaitObservable: IObservable<'T> * IObservable<'U> -> Async<Choice<'T, 'U>> Overload taking two events as parameters let!evt=Async.AwaitObservable (main.MouseLeftButtonDown, main.MouseMove) matchevtwith | Choice1Of2(up) -> // Left button was clicked | Choice2Of2(move) -> // Mouse cursor moved } Returns Choice<'T1,'T2>
  • 25. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 26. Patterns for asynchronous programming Begin/End pattern used by standard libraries Event-based pattern used more recently Can we write this using AwaitObservable? Little tricky – need to attach handler first! lethr=HttpWebRequest.Create("http://...") let!resp=hr.AsyncGetResponse() letsr=resp.GetResponseStream() Created from Begin/EndGetResponse letwc=newWebClient() wc.DownloadStringCompleted.Add(funres-> letstring=res.Result ) wc.DownloadStringAsync("http://...") Register handler and then start
  • 27. Performing asynchronous calls correctly Introducing GuardedAwaitObservableprimitive Calls a function after attaching event handler We cannot accidentally lose event occurrence Mixing asynchronous I/O and GUI code If started from GUI thread, will return to GUI thread We can safely access controls after HTTP request async { letwc=newWebClient() let!res= Async.GuardedAwaitObservablewc.DownloadStringCompleted (fun () ->wc.DownloadStringAsync(newUri(uri))) // (...) }
  • 28. DEMO Social rectangle drawing application web 2.0 inside!!
  • 29. Brief summary of the talk Reactive code can run on the GUI thread! Two programming styles in F# Declarative or data-flow style Using Event.scan combinators Imperative or control-flow style Using AwaitEvent primitive In both cases, we can use diagrams Web requests from workflows Both common patterns work
  • 31. References & Links What do you need to run samples? Samples will be on my blog (below) Get F# and F# PowerPack (http://www.fsharp.net) Get Silverlight Developer tools (F# included!) http://www.silverlight.net/getstarted Blog & contacts “Real-World Functional Programming” http://functional-programming.net My blog: http://tomasp.net/blog Contact: tomas@tomasp.net