Task.Delay Challenge Solution
This post suggest solution to the Task.Delay challenge.
If you haven’t read the Task.Delay challenge you can find it here.
In nutshell the challenge was about making Task.Delay like functionality
which is test-able (using IScheduler for having virtual time).
In order to support virtual time I will use Rx’s stream (which is also awaitable).
The original Task.Delay is actually having 2 different completion path:
– Complete by time.
– Complete as result of cancellation token event.
The general idea of the solution is to have 2 Rx’s streams one for each completion path:
– Timer which will represent completion by time.
– Custom stream which will react to the cancellation token.
I will combine both stream with Observable.Amb operator which will take the values
from the first stream that will produce a value (and unsubscribe from the other stream).
For convenient API access I wrapped the solution with extension methods.
The following code snippet represent the cancellation stream:
The stream was created by using Observable.Create (line 6) combined with registration to the cancellation token event (lines 9-13).
From here it’s all matter of composition (see the following code snippet):