Module: Is::Async

Defined in:
lib/is/async.rb

Overview

public

Makes Ruby objects async-aware.

Instance Method Summary collapse

Instance Method Details

#asyncObject

public

Call asynchronous behavior in a proper async context.



14
15
16
17
18
# File 'lib/is/async.rb', line 14

def async
  ::Async::Reactor.run do |task|
    yield task
  end
end

#awaitObject

public

Call asynchronous behavior synchronously in a proper async context.



22
23
24
25
26
27
28
29
30
# File 'lib/is/async.rb', line 22

def await
  if (task = ::Async::Task.current?)
    yield task
  else
    ::Async::Reactor.run { |task|
      yield task
    }.wait
  end
end

#deferObject

public

Yields control to allow other fibers to execute.



58
59
60
61
62
# File 'lib/is/async.rb', line 58

def defer
  if (task = ::Async::Task.current?)
    task.yield
  end
end

#sleep(seconds) ⇒ Object

public

Sleeps for seconds in a proper async context.



34
35
36
37
38
# File 'lib/is/async.rb', line 34

def sleep(seconds)
  await do |task|
    task.sleep(seconds)
  end
end

#timeout(seconds, &block) ⇒ Object

public

Call asynchonous behavior in a proper async context, wrapped in a timeout.

Raises Core::Async::Timeout if execution exceeds seconds.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/is/async.rb', line 44

def timeout(seconds, &block)
  await do |task|
    if seconds && seconds > 0
      task.with_timeout(seconds, Core::Async::Timeout) do
        yield task
      end
    else
      yield task
    end
  end
end