Class: Reacto::Operations::FlattenLabeled

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

Instance Method Summary collapse

Constructor Details

#initialize(accumulator = nil, initial = NO_VALUE) ⇒ FlattenLabeled

Returns a new instance of FlattenLabeled.



9
10
11
12
# File 'lib/reacto/operations/flatten_labeled.rb', line 9

def initialize(accumulator = nil, initial = NO_VALUE)
  @accumulator = accumulator
  @initial = initial
end

Instance Method Details

#call(tracker) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/reacto/operations/flatten_labeled.rb', line 14

def call(tracker)
  value = -> (v) do
    unless v.is_a?(LabeledTrackable)
      tracker.on_error(ArgumentError.new(
        'Trackable#flatten_labeled expects all values emitted by the ' \
        'source Trackable to be LabeledTrackable instances.'
      ))
      return
    end

    labeled_trackable =
      if @accumulator.nil?
        v.first
      else
        v.inject(@initial, &@accumulator).last
      end

    accumulated = []
    labeled_trackable.on(value: ->(val) { accumulated << val })
    tracker.on_value(
      OpenStruct.new({ label: v.label, value: accumulated.first })
    )
  end

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