4

I need to have an infinite loop on top of eventmachine that constantly reads a redis queue. below is my code. is recursion the right way to do it? I tried loop do loop, but could not make it work that way.

require 'em-hiredis'

def read
  d = @redis.blpop 'queue', 0
  d.callback do |_, value|
    p value
    read
  end.errback do |e|
    p e
    EM.next_tick { read }
  end
end

EM.run do
  @redis = EM::Hiredis.connect
  read
end
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • Never worked with EM directly, but yes, generally something similar to recursion is is what you want to do. Instead of calling function again, you should trigger an event which is handled by function itself. This way you can prevent stack overflow (AFAIK [you can't rely on tail recursion optimization in Ruby](http://stackoverflow.com/questions/824562/does-ruby-perform-tail-call-optimization)). So, if `EM.next_tick` call does what I outlined, it's a good way. – skalee Dec 22 '12 at 10:36

1 Answers1

3

Better to subscribe to redis pub/sub queue. https://gist.github.com/957367 If you really need a loop then EM itself is an infinite loop, you just need to schedule your job again and again with next_tick:

def read
  d = @redis.blpop 'queue', 0
  d.callback do |_, value|
    EM.next_tick { read }
  end.errback do |e|
    EM.next_tick { read }
  end
 end
Sergii Mostovyi
  • 1,361
  • 1
  • 15
  • 19