Created
May 29, 2025 18:31
-
-
Save Ilchert/00265b5734d7f9f78c605e9af8395dd4 to your computer and use it in GitHub Desktop.
Debounce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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