I'm trying to figure out how to process n buffered items from a sequence then wait t seconds before processing the next n items?
Here's a crude form of what I'm trying to do, using Thread.Sleep(). I want to avoid Thread.Sleep() and do it properly.
static void Main(string[] args)
{
var t = Observable.Range(0, 100000);
var query = t.Buffer(20);
query.ObserveOn(NewThreadScheduler.Default)
.Subscribe(x => DoStuff(x));
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
}
static void DoStuff(IList<int> list)
{
Console.WriteLine(DateTime.Now);
foreach (var value in list)
{
Console.WriteLine(value);
}
Thread.Sleep(TimeSpan.FromSeconds(10));
}
Can any one help me find a more RX way of doing this?
Thanks
Flash
// Instantiate this once, we'll use it in a closure multiple times.
var delay = Observable.Empty<int>().Delay(TimeSpan.FromMilliseconds(10));
// start with a source of individual items to be worked.
Observable.Range(0, 100000)
// Create batches of work.
.Buffer(20)
// Select an observable for the batch of work, and concat a delay.
.Select(batch => batch.ToObservable().Concat(delay))
// Concat those together and form a "process, delay, repeat" observable.
.Concat()
// Subscribe!
.Subscribe(Console.WriteLine);
// Make sure we wait for our work to be done.
// There are other ways to sync up, like async / await.
Console.ReadLine();
Alternatively, you could also sync up using async/await:
static IObservable<int> delay = Observable.Empty<int>().Delay(TimeSpan.FromMilliseconds(100));
static async Task Run()
{
await Observable.Range(0, 1000)
.Buffer(20)
.Select(batch => batch.ToObservable().Concat(delay))
.Concat()
.Do(Console.WriteLine)
.LastOrDefaultAsync();
}
Isn't that delay
observable a nifty trick? It works because OnCompleted is delayed just like OnNext!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With