Sha256: 507f053fac5086b0aa45e13f3fff5c6cdfc43e5150c588a7e2831e41480feb03

Contents?: true

Size: 1.43 KB

Versions: 9

Compression:

Stored size: 1.43 KB

Contents

require 'thread'

module Bixby
  module WebSocket

    # Asynchronously receive a response via some channel
    class AsyncResponse

      attr_reader :id

      # Create a new AsyncResponse. Optionally pass a callback block which will
      # be fired when the response is set.
      #
      # @param [String] id
      #
      # @yieldparam [JsonResponse] response
      #
      # @return [AsyncResponse]
      def initialize(id, &block)
        @id = id
        @block = block
        @mutex = Mutex.new
        @cond = ConditionVariable.new
        @response = nil
        @completed = false
      end

      # Set the response and signal any blocking threads. Triggers callback, if
      # one was set.
      #
      # @param [Object] obj       result of request, usually a JsonResponse
      def response=(obj)
        @mutex.synchronize {
          @response = obj
          @completed = true
          @cond.broadcast
        }

        if not @block.nil? then
          @block.call(@response)
        end
      end

      # Has the request completed?
      #
      # @return [Boolean] true if completed
      def completed?
        @completed
      end

      # Retrieve the response, blocking until it is available
      #
      # @return [Object] response data
      def response
        @mutex.synchronize {
          if !@completed then
            @cond.wait(@mutex)
          end
        }
        return @response
      end

    end

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
bixby-common-0.7.1 lib/bixby-common/websocket/async_response.rb
bixby-common-0.7.0 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.6 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.5 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.4 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.3 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.2 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.1 lib/bixby-common/websocket/async_response.rb
bixby-common-0.6.0 lib/bixby-common/websocket/async_response.rb