DebounceMonitoring
DebounceMonitoring copied to clipboard
📑 Add debounce logic for any method in a single line.
DebounceMonitoring
Extensions to filter out repeated function calls caused by false or accidental clicks or touches.
- One-line integration
- Inlined, no method wrapping
- Shareable between multiple platforms
- Automated testing friendly
Installing
Add NuGet package to your .NET Standard 2.0 - compatible project
PM> Install-Package DebounceMonitoring
Usage
using DebounceMonitoring;
Debounce instance methods:
internal class ViewModel
{
public void OnButtonClick()
{
if (this.DebounceHere()) return;
// Handle the click
}
}
snippet source
Debounce lambdas and local functions:
public Command ClickCommand { get; }
public ViewModel()
{
ClickCommand = new Command(() =>
{
if (this.DebounceHere()) return;
// Handle the click
});
}
snippet source
Debounce static methods:
internal class Analytics
{
public static void TrackEvent()
{
if (DebounceMonitor.DebounceHereStatic<Analytics>()) return;
// Send the event
}
}
snippet source
Rx Operator
This library also provides the simplest implementation of the debounce operator for Rx.NET (throttle
in RxJs).

Example:
button.ClickAsObservable()
.Debounce()
.Subscribe(_ => OnButtonClick());
snippet source
Interval
The default debounce interval is 500 ms.
It can be specified as an argument:
this.DebounceHere(intervalMs: 1_000)
IObservable<T>.Debounce(intervalMs: 1_000)
or set globally:
DebounceMonitor.DefaultInterval = TimeSpan.FromSeconds(5);
Disable (for automated testing)
The DebounceMonitor
can be disabled in your base TestFixture.Setup
or globally in ModuleInitializer
with ModuleInitializerAttribute or Fody.ModuleInit.
internal static class UnitTestGlobalSetup
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void SetupDebounceMonitor() => DebounceMonitor.Disabled = true;
}
snippet source
How does it work?
When this.DebounceHere
is called, the call time is mapped to its location (method name + line number) and target (this
in this case).
On the next call, the time is compared to the stored one. If the interval
has not yet passed, then the call is meant to be debounced.
The debounce target (reference) is held weakly, so no memory leaks are caused.
License
This project is licensed under the MIT license - see the LICENSE file for details.