Class: Core::Async::Future

Inherits:
Object
  • Object
show all
Includes:
Is::Inspectable
Defined in:
lib/core/async/future.rb

Overview

public

Represents a future result.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Future

Returns a new instance of Future.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/core/async/future.rb', line 17

def initialize(&block)
  @error = nil
  @result = nil
  @status = :pending
  @raised = false
  @fiber = Fiber.schedule { |filament|
    begin
      @filament = filament
      value = block.call
      @result = resolve_value(value)
      @status = :complete
      @result
    rescue Cancel
      @status = :canceled
      nil
    rescue => error
      @error = error
      @status = :failed
      raise error
    end
  }
end

Instance Attribute Details

#statusObject (readonly)

public

The current status; one of :pending, :failed, :canceled, or :complete.



42
43
44
# File 'lib/core/async/future.rb', line 42

def status
  @status
end

Instance Method Details

#cancelObject

public

Attempt to cancel the future, returning true if successful.



54
55
56
57
58
59
60
# File 'lib/core/async/future.rb', line 54

def cancel
  if pending?
    Fiber.scheduler.cancel(@fiber)
  end

  self
end

#canceled?Boolean

public

Return ‘true` if canceled.

Returns:

  • (Boolean)


160
161
162
# File 'lib/core/async/future.rb', line 160

def canceled?
  @status == :canceled
end

#complete?Boolean

public

Return ‘true` if complete.

Returns:

  • (Boolean)


166
167
168
# File 'lib/core/async/future.rb', line 166

def complete?
  @status == :complete
end

#errorObject

public

Return any error that occurred without re-raising, blocking until available.



135
136
137
# File 'lib/core/async/future.rb', line 135

def error
  @error ||= get_error
end

#failed?Boolean

public

Return ‘true` if failed.

Returns:

  • (Boolean)


154
155
156
# File 'lib/core/async/future.rb', line 154

def failed?
  @status == :failed
end

#pending?Boolean

public

Return ‘true` if pending.

Returns:

  • (Boolean)


148
149
150
# File 'lib/core/async/future.rb', line 148

def pending?
  @status == :pending
end

#resolved?Boolean

public

Return ‘true` if failed or complete.

Returns:

  • (Boolean)


172
173
174
# File 'lib/core/async/future.rb', line 172

def resolved?
  failed? || complete?
end

#resultObject

public

Wait until the result is available, returning the result. Only awaits explicitly awaited children.



64
65
66
# File 'lib/core/async/future.rb', line 64

def result
  resolve(false)
end

#waitObject

public

Wait on the future to resolve (including children), returning self.



46
47
48
49
50
# File 'lib/core/async/future.rb', line 46

def wait
  resolve

  self
end