Class: Nl::Async::Future

Inherits:
Object
  • Object
show all
Defined in:
nl/lib/nl/async/operation.rb

Overview

Future for the result of an already-started, single-reply operation.

Defined Under Namespace

Classes: Sink

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mailbox:, on_close:) ⇒ Future

Returns a new instance of Future.



23
24
25
26
27
28
29
30
# File 'nl/lib/nl/async/operation.rb', line 23

def initialize(mailbox:, on_close:)
  @mailbox = mailbox
  @on_close = on_close
  @mutex = Mutex.new
  @state = :open
  @value = nil
  @error = nil
end

Class Method Details

.build(mailbox: Mailbox.new, on_close: nil) ⇒ Object



18
19
20
21
# File 'nl/lib/nl/async/operation.rb', line 18

def self.build(mailbox: Mailbox.new, on_close: nil)
  operation = new(mailbox:, on_close:)
  [operation, Sink.new(mailbox)]
end

Instance Method Details

#await(timeout: nil) ⇒ Object Also known as: value



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'nl/lib/nl/async/operation.rb', line 33

def await(timeout: nil)
  return terminal_result unless @mutex.synchronize { @state == :open }

  event = @mailbox.pop(timeout:)
  case event
  when Events::Item
    settle_done(event.value)
  when Events::Done
    settle_done(nil)
  when Events::Error
    settle_failed(event.exception)
  end
  @mailbox.close
  terminal_result
rescue ClosedError
  terminal_result
end

#close ⇒ Object

Stops local delivery. The dispatcher still drains the Netlink exchange.



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'nl/lib/nl/async/operation.rb', line 57

def close #: nil
  closed, callback = @mutex.synchronize do
    next [false, nil] if @state != :open

    @state = :closed
    [true, @on_close]
  end
  if closed
    callback&.call
    @mailbox.close
  end
  nil
end

#ready? ⇒ Boolean

: bool

Returns:

  • (Boolean)


52
53
54
# File 'nl/lib/nl/async/operation.rb', line 52

def ready? #: bool
  @mutex.synchronize { @state != :open } || !@mailbox.empty?
end