Fork me on GitHub

Tuesday, February 23, 2010

Simple Reactive Programming in Ruby

Reactive Programming is an interesting programming paradigm based on propogation of changes, data flows. A programming model based on side effects, I think this is especially useful when we need to control the state of one entity based on what goes on in outside itself. For example take the equation


x = 1; y = 3
z = x + y
puts z #<= z = 4


Since z depends on x and y, what will happen when we update value of x or y. z remains same as 4 because z is already computed and stored using the values of x and y. Now if the values of x and y changes z will still remain the same.

But what if you want z to get adjusted depending upon x and y. This is more common problem in everyday programming than we think. Imagine you have to update the GUI based on what is changing in underlying model (MVC?) or take an example of spreadsheet where changing a value in a cell recalculates some other cell based on a formula.

Here is a very simple example of Reactive Programming in Ruby using EventTarget.
Here in this example value of z is x + 2. We evaluate z by setting an initial value for x and then later we change value of x and observe the value of z changed as well.


require 'EventTarget'

module Rx
class Change
attr_accessor :old, :new
end
class ObservableValue
include EventTarget
def initialize(value, on_change)
add_event_listener(:change, &on_change)
self.value = value
end
def value=( v )
change = Change.new
change.old = @value
change.new = v
@value = v
evt = Event.new( :change, change )
dispatch_event( evt )
end
end
end

if $0 == __FILE__
z = 0
on_change = Proc.new {|e| z = e.change.new + 2}
x = Rx::ObservableValue.new(3, on_change)
puts "Initial value of z is #{z}" #<= z=5
x.value = 5
puts "Current value of z is #{z}" # <= z=7
end


This is a very simple and contrived example of Reactive programming but I hope this illustrates the point. The concept is way more powerful and is (Functional Reactive Programming) available in a lot of functional languages like Haskell. Take a look at Reactive Framework in .Net and Javascript, Traits, Trellis in Python or Cells in Common Lisp for more understanding of how Reactive Programming works.

Let me know your thoughts and happy hacking :)