Dee*_*esh 1 .net observablecollection
什么是.Net中的Rx FrameWork我已经阅读了一些文章,但概念对我来说仍然不清楚.任何人都可以用一个实际例子来解释它.
Rx或Reactive Extensions是"LINQ to events".LINQ基于IEnumerable<T>通过迭代从序列中提取项目的位置:
var items = source.Where(x => x.Name == "foobar");
foreach (var item in items)
Console.WriteLine(item);
Run Code Online (Sandbox Code Playgroud)
Rx是基于IObservable<T>您订阅推送给您的一系列事件的位置的反转:
var events = source.Where(x => x.Name == "foobar");
events.Subscribe(item => Console.WriteLine(item));
Run Code Online (Sandbox Code Playgroud)
在LINQ中,您可以通过使用foreach循环来控制迭代,并从序列中提取项目.在Rx中,当它们准备就绪时,会触发事件并将项目推送给您.
Rx添加了许多扩展方法,IObservable<T>正如LINQ添加了许多扩展方法,IEnumerable<T>使您能够编写非常紧凑和清晰的代码来处理异步事件.
让我们想象下面的情景:经过漫长的一天,你和你的朋友进入酒吧解渴.你想要的只是几杯啤酒和一张桌子,你可以在这里讨论各种主题(map-reduce实施,gass价格等).
在池方法(非Rx)中,您将执行以下步骤:
1. Ask bartender for two beers
2. While bartender pours the beer into the glasses you wait by the bar
3. When bartender gives you the beers you take them and find an available table, sit, drink and discuss
Run Code Online (Sandbox Code Playgroud)
使用Rx方法,您将执行以下步骤:
1. Ask the bartender for two beers
2. Bartender starts pouring your beers and you and your frined find an available table, sit and start discussing on various subjects
3. When bartender finishes pouring your beer, a waitress brings the beer to your table and you start drinking it.
Run Code Online (Sandbox Code Playgroud)
现在上面的代码可以翻译成如下代码:
//Non Rx approach
var beers = beerKeg.Take(2); // Here you wait for the bartender to pour the beer
foreach(var beer in beers) // Bartender handles you the beer
GrabBeer(beer);
FindAvailableTable(); // You search for an available table
foreach(var beer in beers) // You drink your beer
beer.Drink();
//Rx approach
var beers = beerKeg.Take(2)
.ToObservable()
.Subscribe(beer => beer.Drink());
// Bartender is pouring the beer but meanwhile you can search for an available table.
// The waitress will bring beer to you.
FindAvailableTable();
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
PS:看看使用LINQPad的区别; 执行非Rx查询并调用Dump()结果 - 结果将显示在网格中.使用Rx执行相同的查询并订阅ObservableCollectionwith x=>x.Dump(); 你会看到每个元素都是单独打印的.
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |