我在理解 Observable.Delay 的工作原理以及何时调用 Dispose() 时遇到问题。熟悉 Rx 的人可以帮忙吗?
以下代码片段:
static void Main(string[] args)
{
var oneNumberEveryFiveSeconds = new SomeObservable();
// Instant echo
oneNumberEveryFiveSeconds.SubscribeOn(Scheduler.ThreadPool).Subscribe(num => Console.WriteLine(num));
// One second delay
oneNumberEveryFiveSeconds.Delay(TimeSpan.FromSeconds(1)).SubscribeOn(Scheduler.ThreadPool).Subscribe(num => Console.WriteLine("...{0}...", num));
// Two second delay
oneNumberEveryFiveSeconds.Delay(TimeSpan.FromSeconds(2)).SubscribeOn(Scheduler.ThreadPool).Subscribe(num => Console.WriteLine("......{0}......", num));
Console.ReadKey();
}
public class SomeObservable : IObservable<int>
{
public IDisposable Subscribe(IObserver<int> o)
{
for (var i = 0; i < 2; i++)
{
o.OnNext(i);
}
o.OnCompleted();
return new DisposableAction(() => { Console.WriteLine("DISPOSED"); });
}
}
public class DisposableAction : IDisposable
{
public DisposableAction(Action dispose)
{
this.dispose = dispose;
}
readonly Action dispose;
public void Dispose()
{
dispose();
}
}
产生以下结果:
0
1
已处置
已处置 已
处置
...0...
...1...
......0......
......1......
我期待它更像:
0
1
弃置
...0...
...1...
弃置
......0......
......1......
弃置
任何想法??