Skip to content

Instantly share code, notes, and snippets.

@Ilchert
Created May 29, 2025 18:31
Show Gist options
  • Save Ilchert/00265b5734d7f9f78c605e9af8395dd4 to your computer and use it in GitHub Desktop.
Save Ilchert/00265b5734d7f9f78c605e9af8395dd4 to your computer and use it in GitHub Desktop.
Debounce
var source = Ints();
await foreach (var item in Debounce(source, TimeSpan.FromSeconds(0.5)))
{
Console.WriteLine($"{DateTime.Now} {item}");
}
static async IAsyncEnumerable<int> Ints()
{
for (int i = 0; i < 80; i += 5)
{
await Task.Delay(i * 10);
yield return i;
}
for (int i = 80; i > 0; i -= 5)
{
await Task.Delay(i * 10);
yield return i;
}
}
static async IAsyncEnumerable<T> Debounce<T>(IAsyncEnumerable<T> source, TimeSpan time)
{
await using var enumerator = source.GetAsyncEnumerator();
if (!await enumerator.MoveNextAsync())
yield break;
while (true)
{
var item = enumerator.Current;
var read = enumerator.MoveNextAsync().AsTask();
var timeout = Task.Delay(time);
if (await Task.WhenAny(read, timeout) == timeout)
yield return item;
if (!await read)
{
await timeout;
yield return item; // last item
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment