Search code examples
c#system.reactive

await with a TestScheduler


I am using the TestScheduler to test and design my sequences however for a snippet like below the TestScheduler hangs while the DefaultScheduler works fine. It may possible to remove await in certain cases but this is not what I want for the obvious reasons. So is there a way to use the TestScheduler and await together?

var testScheduler = new TestScheduler();

var response = await Observable
                    .Return(Unit.Default)
                    .Delay(TimeSpan
                    .FromTicks(1000),testScheduler);

testScheduler.AdvanceBy(1000);
response.ShouldNotBeNull();

Solution

  • Your example never completes with TestScheduler because of await nature. The program will stop at await statement and wait for your observable to return a value. However it will never return because you need to move your test scheduler by calling AdvanceBy function and the call is after blocking await.

    If you await then it will never go further and move your scheduler. I would remove async/await here and go for subscribe. Secondly, you need to use the same TestScheduler instance.

    var ts = new TestScheduler();
    System.Reactive.Unit resp = null;
    
    var obs = Observable
                .Return(System.Reactive.Unit.Default)
                .Delay(TimeSpan.FromTicks(1000),ts)
                .Subscribe(r => { resp = r; });
    
    ts.AdvanceBy(1000);
    resp.ShouldNotBeNull();