Skip to content

Instantly share code, notes, and snippets.

@noseratio
Last active September 6, 2021 13:16
Show Gist options
  • Save noseratio/b5745064ba05d4bcadc861c1a73679f9 to your computer and use it in GitHub Desktop.
Save noseratio/b5745064ba05d4bcadc861c1a73679f9 to your computer and use it in GitHub Desktop.
Rx.NET debouncing and throttling
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
static async IAsyncEnumerable<int> Produce()
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(100);
yield return i;
}
}
// debouncing
var sequence1 = Produce()
.ToObservable()
.Throttle(TimeSpan.FromMilliseconds(250))
.ToAsyncEnumerable();
var list1 = await sequence1.ToListAsync();
Trace.Assert(list1.Count == 1 && list1[0] == 9);
// throttling
var sequence2 = Produce()
.ToObservable()
.Sample(TimeSpan.FromMilliseconds(250))
.ToAsyncEnumerable();
var list2 = await sequence2.ToListAsync();
Trace.Assert(list2.Count == 5 && list2[4] == 9);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment