lib/em-synchrony.rb in em-synchrony-1.0.0 vs lib/em-synchrony.rb in em-synchrony-1.0.1

- old
+ new

@@ -6,10 +6,11 @@ require "fiber" rescue LoadError => error raise error unless defined? Fiber end +require "em-synchrony/core_ext" require "em-synchrony/thread" require "em-synchrony/em-multi" require "em-synchrony/tcpsocket" require "em-synchrony/connection_pool" require "em-synchrony/keyboard" @@ -27,11 +28,11 @@ self.run(context, tail) end module Synchrony - # sync is a close relative to inclineCallbacks from Twisted (Python) + # sync is a close relative to inlineCallbacks from Twisted (Python) # # Synchrony.sync allows you to write sequential code while using asynchronous # or callback-based methods under the hood. Example: # # result = EM::Synchrony.sync EventMachine::HttpRequest.new(URL).get @@ -43,42 +44,64 @@ # either succeeds or fails. You do not need to patch or modify the # Deferrable object, simply pass it to EM::Synchrony.sync # def self.sync(df) f = Fiber.current - xback = proc {|r| + xback = proc do |*args| if f == Fiber.current - return r + return args.size == 1 ? args.first : args else - f.resume r + f.resume(*args) end - } - df.callback &xback - df.errback &xback + end + df.callback(&xback) + df.errback(&xback) + Fiber.yield end - # a Fiber-aware sleep function using an EM timer + + # Fiber-aware sleep function using an EM timer + # + # Execution is stopped for specified amount of seconds + # and then automatically resumed (just like regular sleep) + # except without locking the reactor thread + # def self.sleep(secs) fiber = Fiber.current EM::Timer.new(secs) { fiber.resume } Fiber.yield end + # Fiber-aware EventMachine timer: wraps the passed in + # block within a new fiber context such that you can + # continue using synchrony methods + # def self.add_timer(interval, &blk) EM.add_timer(interval) do Fiber.new { blk.call }.resume end end + # Fiber-aware EventMachine timer: wraps the passed in + # block within a new fiber (new fiber on every invocation) + # to allow you to continue using synchrony methods + # def self.add_periodic_timer(interval, &blk) EM.add_periodic_timer(interval) do Fiber.new { blk.call }.resume end end - - # routes to EM::Synchrony::Keyboard + + # Fiber-aware EM.next_tick convenience function + # + def self.next_tick(&blk) + EM.next_tick { Fiber.new { blk.call }.resume } + end + + # Routes to EM::Synchrony::Keyboard + # def self.gets EventMachine::Synchrony::Keyboard.new.gets end end end