本章提供了一个简单而强大的例子,你可能在过去做过(或者将来可能会做),并以两种方式解决它:传统的事件风格和Rx风格的事件处理流。
-
net中编写事件驱动的应用程序非常直观,但在资源清理和代码可读性方面需要注意。
-
要使用Rx库,需要安装Rx包。大多数情况下,您将安装系统。反应计划。
-
您可以在任何类型的应用程序中使用Rx WPF桌面客户端,asp.net网站或简单的控制台应用程序等。
-
传统的。net事件可以转换为可观察对象。
-
Rx允许您在可观察对象之上编写查询表达式。
-
Rx提供了许多查询操作符,例如使用Where操作符进行过滤,使用Select操作符进行转换等等。
当然,这还没有结束。这只是你旅程的开始。要在应用程序中正确使用Rx并使用所有丰富的操作符,您需要学习它们以及将它们组合在一起的技术,这就是本书的全部内容。
在下一章中,你将学习函数式的思维方式,它与。net内部的核心概念一起,使Rx得以发展
word">using System;
word">using System.Collections.Generic;
word">using System.Linq;
word">using System.Reactive.Linq;
word">using System.Text;
word">using System.Text.Json;
word">using System.Threading.Channels;
word">using System.Threading.Tasks;word">namespace ReactiveDemo;word">class StockTick
{word">public word">string Name { word">get; word">set; }word">public word">float Price { word">get; word">set; }
}word">class StockTicker
{word">public word">event EventHandler<StockTick> StockTick;word">public word">void Trigger(StockTick stockTick){StockTick?.Invoke(word">this, stockTick);}
}word">struct DrasticChange
{word">public DateTime TimeSpan { word">get; word">set; }word">public word">string Name { word">get; word">set; }word">public word">float ChangeRatio { word">get; word">set; }word">public word">float OldPrice { word">get; word">set; }word">public word">float NewPrice { word">get; word">set; }
}word">class StockReactive
{word">public word">static word">void Run(){word">var maxChangeRatio = 0.3f;word">var stockTicker = word">new StockTicker();//获取事件源word">var ticks = Observable.FromEventPattern<EventHandler<StockTick>, StockTick>(h => stockTicker.StockTick += h,h => stockTicker.StockTick -= h).Select(t => t.EventArgs);//模拟筛选股票价格波动,(有个漏洞,若果tickPair[0].Price = 0 怎么办)word">var ticksGroups = word">from tick word">in ticksword">group tick word">by tick.Name word">into companyword">from tickPair word">in company.Buffer(2, 1)word">let changeRatio = DiffPercentage(tickPair[1].Price, tickPair[0].Price)word">where changeRatio > maxChangeRatioword">select word">new DrasticChange{TimeSpan = DateTime.Now,Name = company.Key,ChangeRatio = changeRatio,OldPrice = tickPair[0].Price,NewPrice = tickPair[1].Price};word">var subescribeer = ticksGroups.Subscribe(t => Console.WriteLine($"收到信息:{JsonSerializer.Serialize(t)}"));//制造数据word">for (word">int i = 0; i < 100; i++){word">var stockTick = word">new StockTick(){Name = $"{(i % 3)}Name",Price = i * DateTime.Now.Second,};stockTicker.Trigger(stockTick);}subescribeer.Dispose();}word">static word">float DiffPercentage(word">float f1, word">float f2){word">if (f1 == 0){f1 = 0.0000000000001f;}word">return Math.Abs((f1 - f2) / f1);}
}