Class: Dry::Monads::Lazy
Overview
Lazy is a twin of Task which is always executed on the current thread. The underlying mechanism provided by concurrent-ruby ensures the given computation is evaluated not more than once (compare with the built-in lazy assignement ||= which does not guarantee this).
Defined Under Namespace
Modules: Mixin
Class Method Summary collapse
Instance Method Summary collapse
-
#force ⇒ Lazy
Forces the computation.
- #to_s ⇒ String (also: #inspect)
-
#value! ⇒ Object
(also: #force!)
Forces the compution and returns its value.
Methods inherited from Task
#==, [], #apply, #bind, #complete?, #discard, #fmap, #initialize, #monad, #or, #or_fmap, pure, #to_maybe, #to_monad, #to_result, #value_or, #wait
Constructor Details
This class inherits a constructor from Dry::Monads::Task
Class Method Details
.new(promise = nil, &block) ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/dry/monads/lazy.rb', line 14 def new(promise = nil, &block) if promise super(promise) else super(Concurrent::Promise.new(executor: :immediate, &block)) end end |
Instance Method Details
#force ⇒ Lazy
Forces the computation. Note that if the computation thrown an error it won't be re-raised as opposed to value!/force!.
37 38 39 40 |
# File 'lib/dry/monads/lazy.rb', line 37 def force @promise.execute self end |
#to_s ⇒ String Also known as: inspect
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/dry/monads/lazy.rb', line 43 def to_s state = case promise.state when :fulfilled value!.inspect when :rejected "!#{ promise.reason.inspect }" else '?' end "Lazy(#{ state })" end |
#value! ⇒ Object Also known as: force!
Forces the compution and returns its value.
28 29 30 |
# File 'lib/dry/monads/lazy.rb', line 28 def value! @promise.execute.value! end |