Fix intermittent notification non-delivery

Stephen Paul Weber created

We need to wait until all EventMachine items in flight are complete before we
allow the process to terminate or some of them might not happen.  So when the
process wants to exit, wait until the EM thread is done.  Use next_tick to make
sure our stop command only happens when the EM queue is next clear.

Change summary

lib/blather_notify.rb | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)

Detailed changes

lib/blather_notify.rb 🔗

@@ -15,14 +15,22 @@ module BlatherNotify
 		setup(jid, password, nil, nil, nil, nil, workqueue_count: 0)
 
 		EM.error_handler { |e| warn e.message }
-		Thread.new do
+		@thread = Thread.new do
 			EM.run do
 				client.run
 			end
 		end
 
-		at_exit { shutdown }
+		at_exit { wait_then_exit }
 
 		Timeout.timeout(30) { @ready.pop }
 	end
+
+	def self.wait_then_exit
+		EM.next_tick do
+			shutdown
+			EM.stop
+		end
+		@thread.join
+	end
 end