5

我有一个我正在订阅的 observable。这个可观察对象将返回一个对象,该对象具有一个名为 ActivationType 的属性,该属性可以设置多次。

我想要实现的是在 ActivationType 设置为“Type1”时记录一条消息。但是,如果 ActivationType 设置为“Type2”,则仅记录一次消息,如果 ActivationType 为“Type2”,则在再次记录之前等待 30 秒。

所以如果我有:

myObservable
    .Where(o => o.ActivationType == "Type1" || o.ActivationType == "Type2")  //listen for types 1 and 2
    .Throttle() // ??? somehow only throttle if we are currently looking at Type2
    .Subscribe(Log); //log some stuff

我相信 Throttle() 是我正在寻找的,但不确定如何有条件地触发它。

有什么建议么?

4

2 回答 2

6

啊,对于几乎无法理解的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();
     }
于 2013-03-06T18:28:09.307 回答
2

为什么不只使用两个流?

var baseStream = myObservable.Publish().RefCount(); // evaluate once
var type1 = baseStream.Where(o => o.ActivationType == "Type1");
var type2 = baseStream.Where(o => o.ActivationType == "Type2").Throttle(TimeSpan.FromSeconds(30));

type1.Merge(type2).Subscribe(Log);
于 2013-03-06T17:26:31.417 回答