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
- #evaluated? ⇒ Boolean
-
#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, failed, #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
16 17 18 19 20 21 22 |
# File 'lib/dry/monads/lazy.rb', line 16 def new(promise = nil, &block) if promise super(promise) else super(Concurrent::Promise.new(executor: :immediate, &block)) end end |
Instance Method Details
#evaluated? ⇒ Boolean
45 46 47 |
# File 'lib/dry/monads/lazy.rb', line 45 def evaluated? @promise.complete? end |
#force ⇒ Lazy
Forces the computation. Note that if the computation thrown an error it won’t be re-raised as opposed to value!/force!.
39 40 41 42 |
# File 'lib/dry/monads/lazy.rb', line 39 def force @promise.execute self end |
#to_s ⇒ String Also known as: inspect
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/dry/monads/lazy.rb', line 53 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.
30 31 32 |
# File 'lib/dry/monads/lazy.rb', line 30 def value! @promise.execute.value! end |