Changeset

8649:9246f64d6f1e

util.async: Add once() to create temporary runners
author Matthew Wild <mwild1@gmail.com>
date Thu, 22 Mar 2018 07:56:01 +0000
parents 8648:ca710a71d730
children 8650:2f133b6e8740
files spec/util_async_spec.lua util/async.lua
diffstat 2 files changed, 31 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/spec/util_async_spec.lua	Thu Mar 22 07:46:23 2018 +0000
+++ b/spec/util_async_spec.lua	Thu Mar 22 07:56:01 2018 +0000
@@ -593,4 +593,14 @@
 			assert.spy(r.watchers.error).was_not.called();
 		end);
 	end);
+
+	describe("#once()", function ()
+		it("should work", function ()
+			local f = spy.new(function ()
+				assert.truthy(async.ready());
+			end);
+			async.once(f);
+			assert.spy(f).was.called();
+		end);
+	end);
 end);
--- a/util/async.lua	Thu Mar 22 07:46:23 2018 +0000
+++ b/util/async.lua	Thu Mar 22 07:56:01 2018 +0000
@@ -219,4 +219,24 @@
 	return pcall(checkthread);
 end
 
-return { ready = ready, waiter = waiter, guarder = guarder, runner = runner };
+local once; -- forward declaration
+do
+	local once_watchers = {
+		error = function (_, err)
+			error(err);
+		end;
+	};
+	local function once_runner(func) func(); end
+	function once(func)
+		local r = runner(func, once_watchers);
+		return r:run(func);
+	end
+end
+
+return {
+	once = once;
+	ready = ready;
+	waiter = waiter;
+	guarder = guarder;
+	runner = runner
+};