File: variable.rb

package info (click to toggle)
ruby-async 2.36.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 400 kB
  • sloc: ruby: 1,938; makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,376 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2021-2025, by Samuel Williams.
# Copyright, 2025, by Shopify Inc.

require_relative "condition"

module Async
	# A synchronization primitive that allows one task to wait for another task to resolve a value.
	#
	# @deprecated Use {Async::Promise} instead.
	class Variable
		# Create a new variable.
		#
		# @parameter condition [Condition] The condition to use for synchronization.
		def initialize(condition = Condition.new)
			warn("`Async::Variable` is deprecated, use `Async::Promise` instead.", category: :deprecated, uplevel: 1) if $VERBOSE
			
			@condition = condition
			@value = nil
		end
		
		# Resolve the value.
		#
		# Signals all waiting tasks.
		#
		# @parameter value [Object] The value to resolve.
		def resolve(value = true)
			@value = value
			condition = @condition
			@condition = nil
			
			self.freeze
			
			condition.signal(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?
		end
		
		# Wait for the value to be resolved.
		#
		# @returns [Object] The resolved value.
		def wait
			@condition&.wait
			return @value
		end
		
		# Alias for {#wait}.
		def value
			self.wait
		end
	end
end