everett1992
everett1992

Reputation: 2661

Ruby, waiting for callbacks

I'm writing a mpd client using the ruby-mpd library. It has callback driven event listeners but I don't know how to wait for a callback to be executed.o

require 'ruby-mpd'

puts "started new thread"
mpd = MPD.new('localhost', '6600', callbacks: true)

# MPD#connect and MPD#disconnect fire the `:connection` event.
mpd.on(:connection) do |connection|
  if connection
    puts 'connected...'
  else
    puts 'disconnected'
  end
end

mpd.connect

If I run this line by line in IRB connected will be printed after mpd.connect but if I run it as a script it exits immediately after calling connect (before the callback gets called?) Adding a sleep call at the end of the file doesn't help either.

How can I make this script never exit and wait for a kill signal from the user?

Ok, I looked at the how ruby-mpd implements callbacks. It spawns a thread which loops over a block that updates a status object. If the object changes it emits an event.

I think my initial example missed the change in the connection attribute so that even was never fired.

require 'ruby-mpd'

mpd = MPD.new('localhost', '6600', callbacks: true)

mpd.on(:connection) do
  puts 'connected...'
end

mpd.on(:state) do |state|
  puts state
end

mpd.on(:time) do |elapsed_time, total|
  puts "#{elapsed_time}/#{total}"
end

mpd.connect

while true; end

Upvotes: 2

Views: 940

Answers (1)

maniacalrobot
maniacalrobot

Reputation: 2463

You could wrap the mpd calls in an eventmachine block, this will handle the while true; end loop and not waste cpu cycles. You'll also get all the eventmachine I/O, defer and timer logic thrown in for free?

100% untested code, but it would something like this:

require 'ruby-mpd'

EventMachine.run do

  mpd = MPD.new('localhost', '6600', callbacks: true)

  mpd.on(:connection) do
    puts 'connected...'
  end

  mpd.on(:state) do |state|
    puts state
  end

  mpd.on(:time) do |elapsed_time, total|
    puts "#{elapsed_time}/#{total}"
  end

  mpd.connect

end

Upvotes: 1

Related Questions