class Asynchro::Tracker

Public Class Methods

new() { |self| ... } click to toggle source

Creates a new tracker. If a block is given, this block is called with the new instance as an argument, and the tracker is automatically run.

# File lib/asynchro/tracker.rb, line 4
def initialize
  @sequence = 0
  
  if (block_given?)
    yield(self)
    
    Fiber.new do
      self.run!
    end.resume
  end
end

Public Instance Methods

finish(&block) click to toggle source

Executes this block when all the actions to be performed have checked in as finsished.

# File lib/asynchro/tracker.rb, line 61
def finish(&block)
  (@finish ||= [ ]) << block
end
finished?() click to toggle source

Returns true if this tracker has completed all supplied blocks, or false otherwise.

# File lib/asynchro/tracker.rb, line 67
def finished?
  !@operations or @operations.empty?
end
perform(count = 1, *args) { |callback, *args| ... } click to toggle source

Performs an action. The supplied block will be called with a callback tracking Proc that should be triggered with ‘call` as many times as are specified in the `count` argument. When the correct number of calls have been made, this action is considered finished.

# File lib/asynchro/tracker.rb, line 20
def perform(count = 1, *args)
  @operations ||= { }

  _sequence = @sequence += 1
  @operations[_sequence] = true

  fiber = Fiber.new do
    called = false
    should_resume = false

    callback = lambda {
      called = true

      if (should_resume)
        fiber.resume
      end
    }

    count.times do
      called = false

      yield(callback, *args)

      unless (called)
        should_resume = true
        Fiber.yield
      end
    end

    @operations.delete(_sequence)

    if (self.finished?)
      self.finish!
    end
  end

  (@fibers ||= [ ]) << fiber
end

Protected Instance Methods

finish!() click to toggle source

Executes the defined finish blocks and resumes execution

# File lib/asynchro/tracker.rb, line 84
def finish!
  @finish and @finish.each(&:call)
end
run!() click to toggle source

Runs through the tasks to perform for this tracker. Should only be called if this object is initialized without a supplied block as in that case, this would have been called already.

# File lib/asynchro/tracker.rb, line 75
def run!
  if (self.finished?)
    self.finish!
  else
    @fibers.each(&:resume)
  end
end