Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Last active August 29, 2015 13:55
Show Gist options
  • Save Shinpeim/8770483 to your computer and use it in GitHub Desktop.
Save Shinpeim/8770483 to your computer and use it in GitHub Desktop.
require 'observer'
class ReactiveValue
include Observable
attr_reader :value
def set(value)
@value = value
changed
notify_observers(self)
end
def +(other)
ReactivePlus.new(self, other)
end
end
class ReactivePlus
def initialize(a, b)
@a_value = a.value
a.add_observer(self, :updated_a)
@b_value = b.value
a.add_observer(self, :updated_b)
end
def value
@a_value + @b_value
end
def updated_a(a)
@a_value = a.value
end
def updated_b(b)
@b_value = b.value
end
end
a = ReactiveValue.new
a.set(10)
b = ReactiveValue.new
b.set(10)
c = a + b
p c.value # => 20
a.set(20)
p c.value # => 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment