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
Add NuGet package to your .NET Standard 2.0 - compatible project
PM> Install-Package DebounceMonitoring
using DebounceMonitoring;
internal class ViewModel
{
public void OnButtonClick()
{
if (this.DebounceHere()) return;
// Handle the click
}
}
public Command ClickCommand { get; }
public ViewModel()
{
ClickCommand = new Command(() =>
{
if (this.DebounceHere()) return;
// Handle the click
});
}
internal class Analytics
{
public static void TrackEvent()
{
if (DebounceMonitor.DebounceHereStatic<Analytics>()) return;
// Send the event
}
}
This library also provides the simplest implementation of the debounce operator for Rx.NET (throttle
in RxJs).
Example:
button.ClickAsObservable()
.Debounce()
.Subscribe(_ => OnButtonClick());
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);
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;
}
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.
This project is licensed under the MIT license - see the LICENSE file for details.