Last active
August 29, 2015 13:55
-
-
Save Shinpeim/8770483 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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