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) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/dry/monads/lazy.rb', line 16 def new(promise = nil, &) if promise super(promise) else super(Concurrent::Promise.new(executor: :immediate, &)) end end |
Instance Method Details
#evaluated? ⇒ Boolean
43 |
# File 'lib/dry/monads/lazy.rb', line 43 def evaluated? = @promise.complete? |
#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
49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/dry/monads/lazy.rb', line 49 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 |
# File 'lib/dry/monads/lazy.rb', line 30 def value! = @promise.execute.value! |