啊,对于几乎无法理解的Window
操作员来说,这是一个完美的案例!
编辑:我每个月发布这个链接十几次,我发誓 - 最好的通读我见过的Window
, Join
, Buffer
,GroupJoin
等运算符:
Lee Campbell:Rx 第 9 部分——加入、窗口、缓冲区和组加入
var source = new Subject<Thing>();
var feed = source.Publish().RefCount();
var ofType1 = feed.Where(t => t.ActivationType == "Type1");
var ofType2 = feed
// only window the type2s
.Where(t => t.ActivationType == "Type2")
// our "end window selector" will be a tick 30s off from start
.Window(() => Observable.Timer(TimeSpan.FromSeconds(30)))
// we want the first one in each window...
.Select(lst => lst.Take(1))
// moosh them all back together
.Merge();
// We want all "type 1s" and the buffered outputs of "type 2s"
var query = ofType1.Merge(ofType2);
// Let's set up a fake stream of data
var running = true;
var feeder = Task.Factory.StartNew(
() => {
// until we say stop...
while(running)
{
// pump new Things into the stream every 500ms
source.OnNext(new Thing());
Thread.Sleep(500);
}
});
using(query.Subscribe(Console.WriteLine))
{
// Block until we hit enter so we can see the live output
// from the above subscribe
Console.ReadLine();
// Shutdown our fake feeder
running = false;
feeder.Wait();
}