socketry / async-redis

MIT License
83 stars 18 forks source link

can't keep the subscription running #45

Closed scratchoo closed 1 year ago

scratchoo commented 1 year ago

I use the following method to subscribe to a topic

class Subscription

 def make_redis_endpoint(uri)
    uri = URI(uri)
    tcp_endpoint = Async::IO::Endpoint.tcp(uri.hostname, uri.port)
    return tcp_endpoint
  end

  def client
    endpoint = make_redis_endpoint("redis://localhost:6379/1")
    @client ||= Async::Redis::Client.new(endpoint)
  end

 def subscribe(topic)
    Async do |task|
      condition = Async::Condition.new

      @subscriber = task.async do
        client.subscribe topic do |context|
          condition.signal # We are waiting for messages.

          type, name, message = context.listen

          pp type, name, message
        end
      end
    end
  end

 def publish(topic, msg)
    Async do |task|
      condition = Async::Condition.new

      @publisher = task.async do

        client.publish topic, msg
      end

    end
  end

end

Then I open one terminal and I use it like this:

subscription = Subscription.new
subscription.subscribe('hello')

if I open another terminal and I run

subscription2 = Subscription.new
subscription2.publish('hello', 'world')

I do receive the message in the subscriber side, but it ends immediately, how is it possible to keep the subscriber listening? it's not obvious from the Readme how it works!

thank you.

ioquatix commented 1 year ago

You need to put type, name, message = context.listen in a loop.

I made a complete example for you: https://github.com/socketry/async-redis/blob/main/examples/subscribe/pubsub.rb.