[gjs/ewlsh/main-loop-hooks: 2/2] modules: Add mainloop module for managing the mainloop asynchronously




commit 37a723de79183705f1e5983a0eb989fca7ee68db
Author: Evan Welsh <contact evanwelsh com>
Date:   Sun Feb 27 21:31:59 2022 -0800

    modules: Add mainloop module for managing the mainloop asynchronously

 js.gresource.xml        |  1 +
 modules/esm/mainloop.js | 44 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 45 insertions(+)
---
diff --git a/js.gresource.xml b/js.gresource.xml
index e12dea125..87fd0fa65 100644
--- a/js.gresource.xml
+++ b/js.gresource.xml
@@ -20,6 +20,7 @@
     <file>modules/esm/console.js</file>
     <file>modules/esm/gi.js</file>
     <file>modules/esm/system.js</file>
+    <file>modules/esm/mainloop.js</file>
 
     <!-- Script-based Modules -->
     <file>modules/script/_bootstrap/debugger.js</file>
diff --git a/modules/esm/mainloop.js b/modules/esm/mainloop.js
new file mode 100644
index 000000000..3fd6cc14f
--- /dev/null
+++ b/modules/esm/mainloop.js
@@ -0,0 +1,44 @@
+import GLib from 'gi://GLib';
+
+const {idle_source} = imports.mainloop;
+
+export let mainloop = GLib.MainLoop.new(null, false);
+
+/**
+ * Run the mainloop asynchronously
+ *
+ * @returns {Promise<void>}
+ */
+export function run() {
+    return mainloop.runAsync();
+}
+
+/**
+ * Quit the mainloop
+ */
+export function quit() {
+    if (!mainloop.is_running())
+        throw new Error('Main loop was stopped already');
+
+    mainloop.quit();
+}
+
+/**
+ * Adds an idle task to the mainloop
+ *
+ * @param {(...args) => boolean} handler a callback to call when no higher priority events remain
+ * @param {number} [priority] the priority to queue the task with
+ */
+export function idle(handler, priority) {
+    const source = idle_source(handler, priority);
+    source.attach(null);
+
+    return source;
+}
+
+export default {
+    mainloop,
+    idle,
+    run,
+    quit,
+};


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]