Class: Reacto::Operations::DependOn

Inherits:
Object
  • Object
show all
Defined in:
lib/reacto/operations/depend_on.rb

Instance Method Summary collapse

Constructor Details

#initialize(trackable, key: :data, accumulator: nil) ⇒ DependOn

Returns a new instance of DependOn.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/reacto/operations/depend_on.rb', line 9

def initialize(trackable, key: :data, accumulator: nil)
  @key = key
  @trackable =
    if accumulator.nil?
      trackable.first
    else
      trackable.inject(NO_VALUE, &accumulator)
    end

  @lock = Mutex.new

  @close = false
  @error = nil
end

Instance Method Details

#bufferObject



24
25
26
# File 'lib/reacto/operations/depend_on.rb', line 24

def buffer
  @buffer ||= []
end

#call(tracker) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/reacto/operations/depend_on.rb', line 57

def call(tracker)
  value = ->(v) do
    if @result.nil?
      @lock.synchronize do
        buffer << v

        check_ready_and_track(tracker)
      end
    else
      tracker.on_value(
        OpenStruct.new({ value: v }.merge(@key => @result))
      )
    end
  end

  error = ->(e) do
    if @result.nil?
      @lock.synchronize do
        @error = e

        check_ready_and_track(tracker)
      end
    else
      tracker.on_error(e)
    end
  end

  close = -> do
    if @result.nil?
      @lock.synchronize do
        @close = true

        check_ready_and_track(tracker)
      end
    else
      tracker.on_close
    end
  end

  Subscriptions::OperationSubscription.new(
    tracker, value: value, error: error, close: close
  )
end

#check_ready_and_track(tracker) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/reacto/operations/depend_on.rb', line 44

def check_ready_and_track(tracker)
  depend_value = ->(v) { @result = v }
  depend_error = ->(e) { flush(e) }
  depend_close = -> { flush }

  if @subscription.nil?
    @tracker = tracker
    @subscription = @trackable.on(
      value: depend_value, error: depend_error, close: depend_close
    )
  end
end

#flush(error = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/reacto/operations/depend_on.rb', line 28

def flush(error = nil)
  unless error.nil?
    @tracker.on_error(error)
    return
  end

  buffer.each do |val|
    @tracker.on_value(
      OpenStruct.new({ value: val }.merge(@key => @result))
    )
  end

  @tracker.on_close if @close
  @tracker.on_error(@error) if @error
end