c# – Rx observable,如果某个超时到期,则发布一个值

我有一个返回可观察的方法.这个可观察的应该(如果evetything正常工作)每秒发布一个值.我想要做的是,如果在没有输出的情况下经过了一定时间,它会发布一些自定义警报值.

private IObservable<string> GetStatus()
{
    return statusProvider
                .Subscribe(statusKey)  //returns an IObservable<string>
                .Select(st => st.ToUpper())
                .DistinctUntilChanged()
                .TakeUntil(disposed)
                .Replay(1)
                .RefCount();
}

有没有一种简单的方法让我修改上面的内容,这样如果状态更新没有进入30秒,那么statusProvider会发布“bad”,然后如果之后发生更新,它将像往常一样发布并且计时器是再次重启到30秒?

最佳答案 这是一种方式.启动一个计时器,当它到期时会产生“坏”.每次statusProvider生成状态时,计时器都会重置.

var statusSignal = statusProvider
            .Subscribe(statusKey)  //returns an IObservable<string>
            .Select(st => st.ToUpper())
            .Publish()
            .RefCount();

// An observable that produces "bad" after a delay and then "hangs indefinately" after that
var badTimer = Observable
    .Return("bad")
    .Delay(TimeSpan.FromSeconds(30))
    .Concat(Observable.Never<string>());

// A repeating badTimer that resets the timer whenever a good signal arrives.
// The "indefinite hang" in badTimer prevents this from restarting the timer as soon
// as it produces a "bad".  Which prevents you from getting a string of "bad" messages
// if the statusProvider is silent for many minutes.
var badSignal = badTimer.TakeUntil(statusSignal).Repeat();

// listen to both good and bad signals.
return Observable
    .Merge(statusSignal, badSignal)
    .DistinctUntilChanged()
    .Replay(1)
    .RefCount();
点赞