在OnNext之前调用Observable.Delay调用Dispose

时间:2010-10-20 01:39:06

标签: c# system.reactive reactive-programming

我在理解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 ......
  设置

任何想法??

3 个答案:

答案 0 :(得分:2)

Rx的标准功能是在序列完成时处理订阅(即使其值仍然通过另一个序列传送)。

考虑到这一点,Delay无法控制从源序列发出的值的速度,它只能将值延迟到自己的观察者。

答案 1 :(得分:0)

如果我不得不猜测我会说延迟排队来自原始观察点的物品,然后根据指定的延迟按照它认为合适的方式发送它们。因此,即使原始的可观察性早已被处理,延迟方法创建的可观察性仍然存在并且仍然存在。你正在观察的行为非常适合这种解释。

答案 2 :(得分:-1)

没有ThreadPool,行为是相同的:

0 1 配置 配置 ... 0 ... ... 1 ... ...... 0 ...... ...... 1 ......

相关问题