Skip to content

Commit

Permalink
Variable: add #reject, #rejected? and raise in #wait
Browse files Browse the repository at this point in the history
  • Loading branch information
paddor committed Jan 27, 2025
1 parent 6d22bcf commit d76627f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/async/variable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,40 @@ def resolve(value = true)

condition.signal(value)
end

def reject(error)
@error = error
condition = @condition
@condition = nil

self.freeze

condition.signal # signal without value
end

# Alias for {#resolve}.
def value=(value)
self.resolve(value)
end

# Whether the value has been resolved.
#
# @returns [Boolean] Whether the value has been resolved.
def resolved?
@condition.nil?
@condition.nil? && @error.nil?
end

def rejected?
@condition.nil? && !!@error
end

# Wait for the value to be resolved.
#
# @returns [Object] The resolved value.
# @raises [Exception] The error with which this Variable was rejected
def wait
@condition&.wait
raise @error if @error
return @value
end

Expand Down
24 changes: 24 additions & 0 deletions test/async/variable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,37 @@

variable.resolve(value)
end

it "can wait for the value to be resolved using setter" do
Async do
expect(variable.wait).to be == value
end

variable.value = value
end

it "can't resolve it a 2nd time" do
variable.resolve(value)
expect do
variable.resolve(value)
end.to raise_exception(FrozenError)
end

it "can reject with an exception" do
variable.reject RuntimeError.new("boom")
expect(variable).not.to be(:resolved?)
expect(variable).to be(:rejected?)
end

it "can wait for a rejection with an error" do
Async do
expect do
variable.wait
end.to raise_exception(RuntimeError)
end

variable.reject(RuntimeError.new)
end
end

include Sus::Fixtures::Async::ReactorContext
Expand Down

0 comments on commit d76627f

Please sign in to comment.