我正在尝试学习RX并且正在为两个不同的可观察者订阅一个创建的观察者。
var observer = Observer.Create<string>(x => Console.WriteLine(x), () => Console.WriteLine("Completed")); var subscription1 = Observable.Interval(TimeSpan.FromSeconds(1)) .Select(x => "X" + x) .Subscribe(observer); var subscription2 = Observable.Interval(TimeSpan.FromSeconds(2)) .Select(x => "YY" + x) .Subscribe(observer); Console.WriteLine("Unsubscribing in 5 seconds"); Thread.Sleep(5000); subscription1.Dispose(); subscription2.Dispose(); Console.WriteLine("All disposed");我希望在处理订阅后1,观察员将完成。 我在这里想念的是什么? 目前,我从上面的代码中获得以下控制台输出:
Unsubscribing in 5 seconds X0 YY0 X1 X2 YY1 X3 All disposedI am trying to learn about RX and am subscribing a created observer to two different observables.
var observer = Observer.Create<string>(x => Console.WriteLine(x), () => Console.WriteLine("Completed")); var subscription1 = Observable.Interval(TimeSpan.FromSeconds(1)) .Select(x => "X" + x) .Subscribe(observer); var subscription2 = Observable.Interval(TimeSpan.FromSeconds(2)) .Select(x => "YY" + x) .Subscribe(observer); Console.WriteLine("Unsubscribing in 5 seconds"); Thread.Sleep(5000); subscription1.Dispose(); subscription2.Dispose(); Console.WriteLine("All disposed");I would expect that after disposal of subscription1 the observer would be completed. What am I missing here? Currently I get the following console output from the code above:
Unsubscribing in 5 seconds X0 YY0 X1 X2 YY1 X3 All disposed最满意答案
Observable.Interval创建一个无限序列,因此您永远不会得到“已完成”的消息。 通过取消订阅,您只需停止收听此无限序列。
如果你想完成序列,你可以使用像Observable.Interval(...).Take(3)这样的东西Observable.Interval(...).Take(3) 。
Observable.Interval creates an infinite sequence so you never will get the 'completed' message. By unsubscribing you just stop listening to this infinite sequence.
If you want the sequence to be completed you could use something like Observable.Interval(...).Take(3).
更多推荐
发布评论