Skip to content

Instantly share code, notes, and snippets.

@MrClan
Forked from rhishikeshj/ExtendedEntry.cs
Created July 29, 2020 01:45
Show Gist options
  • Save MrClan/27862f1857ee9756efbb5ab3b0e7b885 to your computer and use it in GitHub Desktop.
Save MrClan/27862f1857ee9756efbb5ab3b0e7b885 to your computer and use it in GitHub Desktop.
How to debounce an Entry control in Xamarin
private Task _debounceTask;
public ExtendedEntry()
{
int debounceDelay = 500;
CancellationTokenSource _debounceTaskCancellationSource = null;
TextChanged += (sender, e) =>
{
if (_debounceTask != null)
{
_debounceTaskCancellationSource.Cancel();
_debounceTaskCancellationSource.Dispose();
_debounceTask = null;
}
var text = Text;
_debounceTaskCancellationSource = new CancellationTokenSource();
_debounceTask = Task.Delay(debounceDelay, _debounceTaskCancellationSource.Token).ContinueWith((task) =>
{
if (_debounceTaskCancellationSource.IsCancellationRequested == false)
{
if (text.Equals(Text))
{
DebouncedTextChanged.Invoke(sender, new TextChangedEventArgs(text, Text));
}
}
_debounceTask = null;
_debounceTaskCancellationSource.Dispose();
});
};
}
public event EventHandler<TextChangedEventArgs> DebouncedTextChanged;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment