From 3e6de5c8dd5f8c005a331a584ab7720e8745d7da Mon Sep 17 00:00:00 2001 From: Xenira <1288524+Xenira@users.noreply.github.com> Date: Wed, 6 Mar 2024 23:19:11 +0100 Subject: [PATCH] feat(callback): add callback utils (#18) --- plugin/src/util/Callbacks.cs | 45 ++++++++++++++++++++++++++++++++++++ plugin/src/util/Debouncer.cs | 22 ------------------ 2 files changed, 45 insertions(+), 22 deletions(-) create mode 100644 plugin/src/util/Callbacks.cs delete mode 100644 plugin/src/util/Debouncer.cs diff --git a/plugin/src/util/Callbacks.cs b/plugin/src/util/Callbacks.cs new file mode 100644 index 0000000..71c764f --- /dev/null +++ b/plugin/src/util/Callbacks.cs @@ -0,0 +1,45 @@ +using System; +using System.Linq; +using UnityEngine; + +namespace PiUtils.Util; + +public class Callbacks +{ + public static Action Debounce(Action callback, float seconds) + { + Coroutine timeout = null; + T lastValue; + + return (T arg) => + { + lastValue = arg; + if (timeout != null) + { + return; + } + + timeout = AsyncGameObject.Timeout(() => + { + timeout = null; + callback(lastValue); + }, seconds); + }; + } + + public static Action Unique(Action callback) + { + Option lastValue = Option.None(); + + return (T arg) => + { + if (lastValue.Contains(arg)) + { + return; + } + + lastValue = Option.Some(arg); + callback(arg); + }; + } +} diff --git a/plugin/src/util/Debouncer.cs b/plugin/src/util/Debouncer.cs deleted file mode 100644 index 9feb94e..0000000 --- a/plugin/src/util/Debouncer.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using UnityEngine; - -namespace PiUtils.Util; - -public class Debouncer -{ - public static Action Debounce(Action callback, float seconds) - { - Coroutine timeout = null; - - return (T arg) => - { - if (timeout != null) - { - AsyncGameObject.Cancel(timeout); - } - - timeout = AsyncGameObject.Timeout(() => callback(arg), seconds); - }; - } -}