Rx 处理订阅
处理循环中创建的订阅的推荐方法是什么? 在下面的示例中,我在 for 循环中生成订阅,并将它们添加到 List
中,并通过 foreaching 在 List
上显式地处理它们 这对我来说似乎有点难闻,我认为必须有一种更干净的方法来清理订阅,除非 GC 在运行时处理它们。我需要明确处置订阅吗?
class Program
{
static void Main(string[] args)
{
Func<int, IEnumerable<int>> func = x =>
{
return Enumerable.Range(0, x);
};
List<IDisposable> subsriptions = new List<IDisposable>();
for (int i = 1; i < 10; i++)
{
var observable = func(i).ToObservable().ToList();
var subscription = observable.Subscribe(x => Console.WriteLine(x.Select(y => y.ToString()).Aggregate((s1, s2) => s1 + "," + s2)));
subsriptions.Add(subscription);
}
Console.ReadLine();
subsriptions.ForEach(s => s.Dispose());
}
}
What is the recommended way to dispose of subscriptions that are created in a loop?
In the following contrived example I'm generating subscriptions in a for loop and adding them to a List
and disposing them explicity by for eaching over the List
This seems a bit smelly to me and I'm thinking that there has to be a cleaner way to clean up the subscriptions unless the GC disposes them when it runs. Do I need to explicity Dispose the subscriptions?
class Program
{
static void Main(string[] args)
{
Func<int, IEnumerable<int>> func = x =>
{
return Enumerable.Range(0, x);
};
List<IDisposable> subsriptions = new List<IDisposable>();
for (int i = 1; i < 10; i++)
{
var observable = func(i).ToObservable().ToList();
var subscription = observable.Subscribe(x => Console.WriteLine(x.Select(y => y.ToString()).Aggregate((s1, s2) => s1 + "," + s2)));
subsriptions.Add(subscription);
}
Console.ReadLine();
subsriptions.ForEach(s => s.Dispose());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果源完成,则无需处置订阅。在您的示例中,如果您想在完成之前停止枚举
Range
,则只需处置订阅。即使在这种情况下,更常见的做法是使用终止订阅的运算符(作为其设计的一部分)来处理订阅,例如
Take
、TakeWhile
、TakeUntil
代码>.如果您确实想要组合多个
IDisposable
订阅,CompositeDisposable
的设计正是为了实现这一目的:Subscriptions do not need to be disposed if the source completes. In your example, you would only dispose the subscription if you wanted to stop enumerating the
Range
before it was finished.Even in that situation, it's more common to dispose of subscriptions by using an operator that terminates the subscription as part of its design like
Take
,TakeWhile
,TakeUntil
.If you do want to combine several
IDisposable
subscriptions,CompositeDisposable
is designed to do exactly that: