【问题标题】:Transforming a sequence of events into a more granular sequence of values将一系列事件转换为更细粒度的值序列
【发布时间】:2013-01-11 07:00:31
【问题描述】:

简而言之,我正在尝试使用响应式库来实现一个简单的尾部实用程序,以便在新行附加到文件时主动监控它们。这是我到目前为止得到的:

    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,该事件在文件大小更改时触发。从那里,我确定哪些行是新的,并且 observable 返回一个新行列表。理想情况下,可观察序列将只是一个代表每个新行的字符串。可观察返回列表的唯一原因是因为我根本不知道如何按摩它来做到这一点。任何帮助将不胜感激。

【问题讨论】:

    标签: c# system.reactive


    【解决方案1】:

    你可以使用SelectMany:

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

    【讨论】:

    • 我知道这很简单。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多