I'm writing a UI where the user can type in a search term and a list get continuously updated offering suggestions.
My first though was that the Rx primitive Throttle was a perfect match but it gets me half there.
The suggestions take a while to fetch so I get them asynchronously on not on the UI thread.
The problem is that I want to discard/skip/throw away a result if the user types af the throttle time span again.
For example:
- Time starts and the user presses a key : 0ms
- The throttle is set to 100ms.
- The fetch takes 200ms.
- At 150ms the user pressed another key
Now with Throttle the first fetch will still go ahead an populate the gui suggestion list. What I like to learn is how can I cancel that first fetch as it is not relevant anymore? Only the second keypress should trigger an update to the gui.
Here is what I tried
(I use ReactiveUI but the Q is about Rx)
public IEnumerable<usp_getOpdrachtgevers_Result> Results { get; set; } // [Reactive] pu
public SearchOpdrachtgeverVM()
{
this.WhenAnyValue(x => x.FirstName,
x => x.LastName
)
.Throttle(TimeSpan.FromMilliseconds(200))
.Subscribe(async vm => Results = await PopulateGrid());
}
private async Task<IEnumerable<usp_getOpdrachtgevers_Result>> PopulateGrid()
{
return await Task.Run(
() => _opdrachtgeversCache
.Where(x =>
x.vNaam.Contains(FirstName)
&& x.vLastName.Contains(LastName)
)
);
}