United Kingdom: +44 (0)208 088 8978

Reactive programming in F#

Tom give a brief introduction to reactive programming with F#

We're hiring Software Developers

Click here to find out more

Functional programming and reactive programming are two paradigms that, when combined, enable you to write highly responsive, composable, and predictable code. Functional programming focuses on the use of pure functions and immutability, while reactive programming emphasizes the use of reactive data streams and the propagation of changes. Together, these paradigms provide powerful tools for creating efficient and maintainable code.

F# provides support for reactive programming through the use of the F# Reactive (FSharp.Control.Reactive) library. The F# Reactive library provides a set of functions and types that allow you to create, manipulate, and compose reactive data streams. It also provides a set of operators that allow you to filter, map, and reduce data streams, as well as create new data streams from existing ones.

An example of using the F# Reactive library is creating an observable data stream from a list of integers, and then mapping and filtering the stream to produce a new stream of even numbers only.

open FSharp.Control.Reactive

let numbers = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

// Creating an observable stream from a list
let numberObservable = Observable.ofList numbers

// Mapping the stream to double the value
let doubledObservable = numberObservable |> Observable.map (fun x -> x * 2)

// Filtering the stream to keep even numbers only
let evenObservable = doubledObservable |> Observable.filter (fun x -> x % 2 = 0)

// Subscribing to the stream
evenObservable.Subscribe(printfn "Even number: %d")

This code creates an observable stream from the numbers list, maps the stream to double the value of each number and filters the stream to keep even numbers only. Finally, it subscribes to the stream and prints the even numbers.

Another example is using reactive programming to handle user inputs, such as key presses. The following code is an example of handling key press events by creating an event stream and subscribing to it.

open FSharp.Control.Reactive

// Creating an event stream from key presses
let keyPressEvent = Event.scan (fun _ k -> k) (Key.A) Window.KeyDown

// Subscribing to the event stream
let subscription = keyPressEvent.Add (fun k -> printfn "Key pressed: %A" k)

This code creates an event stream of key presses by using the Event.scan function, which scans the Window.KeyDown event and accumulates the key press values. Then it subscribes to the event stream and prints the key press values.


In summary, reactive programming is a paradigm that uses reactive data streams and change propagation. F# offers support for reactive programming through the F# Reactive library, which enables developers to easily create and manipulate data streams, handle events and write responsive, composable and predictable code.