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

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
 
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-1
AmIt Prasad
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
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
 
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 2014
Phillip 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 - Kalamassery
SHAMJITH KM
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd 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 Loops
P3 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 syllabus
DhivyaSubramaniyam
 
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
 
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
climatewarrior
 

What's hot (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
 

Viewers also liked

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 Everyone
Iulian Dogariu
 
Firebird meets NoSQL
Firebird meets NoSQLFirebird meets NoSQL
Firebird meets NoSQL
Mind The Firebird
 

Viewers also liked (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
 

Similar to 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
 
Intro to RX
Intro to RXIntro to RX
Intro to RX
Scott Weinstein
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
Riccardo Terrell
 
Event
EventEvent
Event
mussawir20
 
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) Data
greenwop
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
Brian Moschel
 
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
Kris Verlaenen
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
SoftServe
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflows
mdlm
 
ReactJS
ReactJSReactJS
ReactJS
Kamlesh Singh
 
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
Randy Connolly
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementation
davejohnson
 
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
Jonas Follesø
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
Nataliya 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 Platform
Javeline B.V.
 

Similar to 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
 

More from 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 Lawrence
Skills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
Skills 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 jvm
Skills 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 cucumberl
Skills 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.js
Skills 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 world
Skills 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_testing
Skills 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 parallelism
Skills 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
 

More from 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
 

Recently uploaded

National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
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
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
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
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
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
 
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
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
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
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
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
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
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?
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
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
 
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
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
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
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

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