Skip to main content
 首页 » 编程设计

c#之使用 Observable.SelectMany 忽略源集合中除最新项目外的所有项目

2024年02月04日29虾米哥

给定

// observable getting files in folder as they are created 
IObservable<string> files = GetFilesAsTheyAreCreated(); 

和函数

// gets lines of the file as they are written 
IObservable<string> GetLines(string filePath) 

我想创建一个 observable,它返回写入最后创建的文件的行。随着更新文件的创建,我想开始从该文件中获取行。现在我有以下代码:

var lines = files.SelectMany(f => GetLines(f)); 

问题是我也将所有行都添加到了旧文件中。有没有办法忽略那些旧行?

注意:我最感兴趣的是取消 GetLines observable,因为它正在新线程上运行。

这可以通过内置运算符实现吗?

请您参考如下方法:

你需要的非常简单:

var lines = files.Select(f => GetLines(f)).Switch(); 

.Switch()运算符(operator)转动 IObservable<IObservable<T>>进入IObservable<T>通过仅从最近的外部可观察对象返回内部值。正是您想要的。