From 1128cbd906e3c81cff6ebda89ea50685c2b2ae9d Mon Sep 17 00:00:00 2001 From: Christopher Vollick <0@psycoti.ca> Date: Mon, 23 Jan 2023 18:02:35 -0500 Subject: [PATCH] Allow Running BlatherNotify in Reactor All of the other scripts spin up the reactor in another thread, and then they do stuff on this thread and use that reactor to have things happen, so they are happy to have BlatherNotify handle the reactor. The script I have coming, though, will instead use EM in the course of it's operation, so it's beneficial that I be able to spin up BlatherNotify in my reactor which allows me to block until the process is done there. --- lib/blather_notify.rb | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) 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) }