将事件序列转换为更细粒度的值序列

本文关键字:细粒度 转换 事件 | 更新日期: 2023-09-27 17:51:13

简而言之,我尝试使用Reactive Library来实现一个简单的tail实用程序,以便在添加到文件中时主动监视新行。以下是我目前得到的结果:

    static void Main(string[] args)
    {
        var filePath = @"C:'Users'wbrian'Documents'";
        var fileName = "TestFile.txt";
        var fullFilePath = filePath + fileName;
        var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        var sr = new StreamReader(fs, true);
        sr.ReadToEnd();
        var lastPos = fs.Position;
        var watcher = new FileSystemWatcher(filePath, fileName);
        watcher.NotifyFilter = NotifyFilters.Size;
        watcher.EnableRaisingEvents = true;
        Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
            action => watcher.Changed += action,
            action => watcher.Changed -= action)
             .Throttle(TimeSpan.FromSeconds(1))
             .Select(e =>
                 {
                     var curSize = new FileInfo(fullFilePath).Length;
                     if (curSize < lastPos)
                     {
                         //we assume the file has been cleared,
                         //reset the position of the stream to the beginning.
                         fs.Seek(0, SeekOrigin.Begin);
                     }
                    var lines = new List<string>();
                    string line;
                    while((line = sr.ReadLine()) != null)
                    {
                        if(!string.IsNullOrWhiteSpace(line))
                        {
                            lines.Add(line);
                        }
                    }
                     lastPos = fs.Position;
                     return lines;
                 }).Subscribe(Observer.Create<List<string>>(lines =>
                 {
                     foreach (var line in lines)
                     {
                         Console.WriteLine("new line = {0}", line);
                     }
                 }));
        Console.ReadLine();
        sr.Close();
        fs.Close();
    }

正如你所看到的,我从FileWatcher事件中创建了一个Observable,这个事件在文件大小被改变时触发。从那里,我确定哪些行是新的,并且可观察对象返回一个新行列表。理想情况下,可观察序列应该只是一个代表每一行的字符串。可观察对象返回List的唯一原因是我根本不知道如何让它这样做。

将事件序列转换为更细粒度的值序列

您可以使用SelectMany:

SelectMany(lines => lines)
.Subscribe(Observer.Create<string>(line => { Console.WriteLine("new line = {0}", line); });