Class: Philiprehberger::Debounce::Coalescer

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/debounce/coalescer.rb

Overview

Collects arguments from multiple calls and passes them as an array to a single block invocation after the wait period.

Instance Method Summary collapse

Constructor Details

#initialize(wait:, on_error: nil, &block) ⇒ Coalescer

Returns a new instance of Coalescer.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/philiprehberger/debounce/coalescer.rb', line 8

def initialize(wait:, on_error: nil, &block)
  raise ArgumentError, 'Block is required' unless block
  raise ArgumentError, 'Wait must be a positive number' unless wait.is_a?(Numeric) && wait.positive?

  @wait = wait
  @block = block
  @on_error = on_error
  @queue = []
  @mutex = Mutex.new
  @timer = nil
  @generation = 0
end

Instance Method Details

#call(*args) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/philiprehberger/debounce/coalescer.rb', line 21

def call(*args)
  @mutex.synchronize do
    @queue << args
    @generation += 1
    schedule_flush(@generation)
  end
end

#cancelObject



41
42
43
44
45
46
# File 'lib/philiprehberger/debounce/coalescer.rb', line 41

def cancel
  @mutex.synchronize do
    @queue.clear
    @generation += 1
  end
end

#flushObject



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/philiprehberger/debounce/coalescer.rb', line 29

def flush
  items = nil
  @mutex.synchronize do
    return if @queue.empty?

    items = @queue.dup
    @queue.clear
    @generation += 1
  end
  invoke_block(items)
end

#pending_argsArray<Array>

Return a snapshot of the queued argument arrays.

Returns:

  • (Array<Array>)

    copy of the current batch queue



55
56
57
# File 'lib/philiprehberger/debounce/coalescer.rb', line 55

def pending_args
  @mutex.synchronize { @queue.dup }
end

#pending_countObject



48
49
50
# File 'lib/philiprehberger/debounce/coalescer.rb', line 48

def pending_count
  @mutex.synchronize { @queue.length }
end