Last active
September 6, 2021 13:16
-
-
Save noseratio/b5745064ba05d4bcadc861c1a73679f9 to your computer and use it in GitHub Desktop.
Rx.NET debouncing and throttling
This file contains 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
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