gpt4 book ai didi

c# - 仅在满足特定条件时 throttle

转载 作者:太空狗 更新时间:2023-10-30 00:32:51 24 4
gpt4 key购买 nike

我有一个正在订阅的 Observable。这个 obsevable 将返回一个对象,该对象具有一个名为 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() 是我正在寻找的,但我不确定如何有条件地触发它。

有什么建议吗?

最佳答案

啊,对于几乎不可能理解的 Window 运算符来说,这是一个完美的案例!

编辑:我发誓,我每个月都会发布这个链接十几次,这是我见过的关于 WindowJoinBuffer 的最佳阅读体验, GroupJoin 等运算符:

Lee Campbell: Rx Part 9–Join, Window, Buffer and Group Join

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();
}

关于c# - 仅在满足特定条件时 throttle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15253675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com