订阅多个observable的Observer未完成(Observer subscribed to multiple observables is not completed)

编程入门 行业动态 更新时间:2024-10-25 11:25:50
订阅多个observable的Observer未完成(Observer subscribed to multiple observables is not completed)

我正在尝试学习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 disposed

I 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).

更多推荐

本文发布于:2023-07-29 14:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316788.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   未完成   Observer   observable   completed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!