Class: ThomasUtils::Future
- Inherits:
-
Object
- Object
- ThomasUtils::Future
- Defined in:
- lib/thomas_utils/future.rb
Constant Summary collapse
- DEFAULT_EXECUTOR =
::Concurrent::CachedThreadPool.new
Instance Method Summary collapse
- #get ⇒ Object
-
#initialize(options = {}) ⇒ Future
constructor
A new instance of Future.
- #join ⇒ Object
- #on_failure(&block) ⇒ Object
- #on_success(&block) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Future
Returns a new instance of Future.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/thomas_utils/future.rb', line 5 def initialize( = {}) [:executor] ||= DEFAULT_EXECUTOR @mutex = Mutex.new @future = ::Concurrent::Future.execute(executor: [:executor]) do begin @result = yield @result = @result.get if @result.is_a?(FutureWrapper) @mutex.synchronize { @success_callback.call(@result) if @success_callback } @result rescue => e @error = e @mutex.synchronize { @failure_callback.call(e) if @failure_callback } end end end |
Instance Method Details
#get ⇒ Object
22 23 24 25 26 |
# File 'lib/thomas_utils/future.rb', line 22 def get result = @future.value raise @error if @error result end |
#join ⇒ Object
28 29 30 |
# File 'lib/thomas_utils/future.rb', line 28 def join get rescue nil end |
#on_failure(&block) ⇒ Object
37 38 39 40 |
# File 'lib/thomas_utils/future.rb', line 37 def on_failure(&block) @mutex.synchronize { @failure_callback = block } @failure_callback.call(@error) if @future.fulfilled? && @error end |
#on_success(&block) ⇒ Object
32 33 34 35 |
# File 'lib/thomas_utils/future.rb', line 32 def on_success(&block) @mutex.synchronize { @success_callback = block } @success_callback.call(@result) if @future.fulfilled? && !@error end |