Class: LightIO::Core::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/lightio/core/future.rb

Overview

Provide a safe way to transfer beam/fiber control flow.

@Example:

future = Future.new
# future#value will block current beam
Beam.new{future.value}
# use transfer to set value
future.transfer(1)

Instance Method Summary collapse

Constructor Details

#initializeFuture

Returns a new instance of Future.



11
12
13
14
15
16
# File 'lib/lightio/core/future.rb', line 11

def initialize
  @value = nil
  @ioloop = IOloop.current
  @state = :init
  @light_fiber = nil
end

Instance Method Details

#done?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/lightio/core/future.rb', line 18

def done?
  @state == :done
end

#transfer(value = nil) ⇒ Object

Transfer and set result value

use this method to set back result

Raises:



25
26
27
28
29
30
# File 'lib/lightio/core/future.rb', line 25

def transfer(value=nil)
  raise LightIO::Error, "state error" if done?
  @value = value
  done!
  @light_fiber.transfer if @light_fiber
end

#valueObject

Get value

this method will block current beam/fiber, until future result is set.

Raises:



39
40
41
42
43
44
45
# File 'lib/lightio/core/future.rb', line 39

def value
  return @value if done?
  raise LightIO::Error, 'already used' if @light_fiber
  @light_fiber = LightFiber.current
  @ioloop.transfer
  @value
end

#value=(value) ⇒ Object



32
33
34
# File 'lib/lightio/core/future.rb', line 32

def value=(value)
  transfer(value)
end