diff --git a/lib/blather_notify.rb b/lib/blather_notify.rb index 309f9e59eb05c0fd614b68b64c556345cd9b9c3f..6c5716cd3655cd28e94184818cd0c611efbe7e83 100644 --- a/lib/blather_notify.rb +++ b/lib/blather_notify.rb @@ -49,14 +49,22 @@ module BlatherNotify EM.error_handler(&method(:panic)) - @thread = Thread.new { - EM.run do - client.run - end - } + EM.next_tick { client.run } - Timeout.timeout(30) { @ready.pop } - at_exit { wait_then_exit } + block_until_ready + end + + def self.block_until_ready + if EM.reactor_running? + promise = EMPromise.new + disconnected { true.tap { EM.next_tick { EM.stop } } } + Thread.new { promise.fulfill(@ready.pop) } + timeout_promise(promise, timeout: 30) + else + @thread = Thread.new { EM.run } + Timeout.timeout(30) { @ready.pop } + at_exit { wait_then_exit } + end end def self.panic(e) @@ -69,11 +77,11 @@ module BlatherNotify disconnected { EM.stop } EM.add_timer(30) { EM.stop } shutdown - @thread.join + @thread&.join end def self.timeout_promise(promise, timeout: 15) - timer = EM.add_timer(timeout) { + timer = EventMachine::Timer.new(timeout) { promise.reject(:timeout) }