Skip to content

Commit 39b650a

Browse files
committed
Add support for await as in Clojure
1 parent af42352 commit 39b650a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/concurrent/agent.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,16 @@ def <<(block)
156156
self
157157
end
158158

159+
# Waits/blocks until all the updates sent before this call are done.
160+
#
161+
# @param [Numeric] timeout the maximum time in second to wait.
162+
# @return [Boolean] false on timeout, true otherwise
163+
def await(timeout = nil)
164+
done = Event.new
165+
post { done.set }
166+
done.wait timeout
167+
end
168+
159169
private
160170

161171
# @!visibility private
@@ -168,6 +178,7 @@ def try_rescue(ex) # :nodoc:
168178
end
169179
rescuer.block.call(ex) if rescuer
170180
rescue Exception => ex
181+
# puts "#{ex} (#{ex.class})\n#{ex.backtrace.join("\n")}"
171182
# supress
172183
end
173184

spec/concurrent/agent_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,25 @@ def trigger_observable(observable)
167167
agent.post { |old| old + 1 }
168168
agent.value.should eq 2
169169
end
170+
171+
end
172+
173+
context '#await' do
174+
175+
it 'waits until already sent updates are done' do
176+
fn = false
177+
subject.post { fn = true; sleep 0.1 }
178+
subject.await
179+
fn.should be_true
180+
end
181+
182+
it 'does not waits until updates sent after are done' do
183+
fn = false
184+
subject.await
185+
subject.post { fn = true; sleep 0.1 }
186+
fn.should be_false
187+
end
188+
170189
end
171190

172191
context 'fulfillment' do

0 commit comments

Comments
 (0)