Class: Reacto::Operations::SliceWhen

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

Instance Method Summary collapse

Constructor Details

#initialize(predicate) ⇒ SliceWhen

Returns a new instance of SliceWhen.



7
8
9
# File 'lib/reacto/operations/slice_when.rb', line 7

def initialize(predicate)
  @predicate = predicate
end

Instance Method Details

#call(tracker) ⇒ Object



11
12
13
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
# File 'lib/reacto/operations/slice_when.rb', line 11

def call(tracker)
  previous = NO_VALUE
  buffer = []

  behaviour = -> (val) do
    if previous != NO_VALUE && @predicate.call(previous, val)
      tracker.on_value(Trackable.enumerable(buffer))
      buffer = []
    end

    buffer << val
    previous = val
  end

  error = -> (e) do
    tracker.on_value(Trackable.enumerable(buffer)) unless buffer.empty?
    tracker.on_error(e)
  end

  close = -> () do
    tracker.on_value(Trackable.enumerable(buffer)) unless buffer.empty?
    tracker.on_close
  end

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