Sha256: 07194f85ebdd0f4680d8e7fd850d777f55a66581efd670c388bc305f01f3f30c

Contents?: true

Size: 1.4 KB

Versions: 10

Compression:

Stored size: 1.4 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.signal
        }

        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
        return @response if @completed
        @mutex.synchronize { @cond.wait(@mutex) }
        return @response
      end

    end

  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
bixby-common-0.5.0 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.13 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.12 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.11 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.10 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.9 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.8 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.7 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.6 lib/bixby-common/websocket/async_response.rb
bixby-common-0.4.5 lib/bixby-common/websocket/async_response.rb