I am creating and Search Text and want my application to perform search every 2 seconds or when there are at least 3 characters in the textbox.
I am trying to use Reactive Extension's buffer or throttle to achieve the same. But I might not be clear about how these two methods work. The code I am trying is
var observableSequence = SearchQueryText.ToObservable();
observableSequence.Buffer(TimeSpan.FromSeconds(2),3).Subscribe(u =>
{
PerformSearch();
});
For me neither these methods wait for 2 seconds nor Buffer halt to get atleast three characters in it.
But in case of buffer if I use the "u" to check for count or average then it returns correct value.
I just want these methods to wait for the time specified in TimeSpan or wait for till the characters reach the specified length.
Best How To :
Buffer works by propagating a result when either the count limit is reached, or when the timespan has elapsed.
You probably want something like this:
observableSequence
.Where(x => x.Length > 2)
.DistinctUntilChanged()
.CombineLatest(Observable.Timer(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2)), (a, b) => a)
.Subscribe(x => Console.WriteLine(x), ex => Console.WriteLine(ex));
This will perform a search every 2 seconds with the most recent search term that satisfied the length criteria. It will do nothing until there is at least 1 search term of the correct length. Is that what you were after?
Or were you just looking to make sure searches were executed no more frequently than every 2 seconds?
In which case:
sequenceObservable
.Where(x => !string.IsNullOrEmpty(x))
.Where(x => x.Length > 2)
.Throttle(TimeSpan.FromSeconds(2))
.DistinctUntilChanged()