Class: Bixby::WebSocket::AsyncResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/bixby-common/websocket/async_response.rb

Overview

Asynchronously receive a response via some channel

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id) {|response| ... } ⇒ AsyncResponse

Create a new AsyncResponse. Optionally pass a callback block which will be fired when the response is set.

Parameters:

  • id (String)

Yield Parameters:



20
21
22
23
24
25
26
27
# File 'lib/bixby-common/websocket/async_response.rb', line 20

def initialize(id, &block)
  @id = id
  @block = block
  @mutex = Mutex.new
  @cond = ConditionVariable.new
  @response = nil
  @completed = false
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



10
11
12
# File 'lib/bixby-common/websocket/async_response.rb', line 10

def id
  @id
end

Instance Method Details

#completed?Boolean

Has the request completed?

Returns:

  • (Boolean)

    true if completed



48
49
50
# File 'lib/bixby-common/websocket/async_response.rb', line 48

def completed?
  @completed
end

#responseObject

Retrieve the response, blocking until it is available

Returns:

  • (Object)

    response data



55
56
57
58
59
60
61
62
# File 'lib/bixby-common/websocket/async_response.rb', line 55

def response
  @mutex.synchronize {
    if !@completed then
      @cond.wait(@mutex)
    end
  }
  return @response
end

#response=(obj) ⇒ Object

Set the response and signal any blocking threads. Triggers callback, if one was set.

Parameters:

  • obj (Object)

    result of request, usually a JsonResponse



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bixby-common/websocket/async_response.rb', line 33

def response=(obj)
  @mutex.synchronize {
    @response = obj
    @completed = true
    @cond.broadcast
  }

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