仅在满足某些条件时发出一个值,否则发出另一个 vlaue



我有一个视图模型,其中包含以下内容:

enum Detection {NotTriggered, Triggered};

public Detection AlertState => _alertState.Value;

public DateTimeOffset? LastAlertTime => _lastAlertTime.Value;

我想做的是拥有另一个属性:默认情况下返回0int AcknowledgementPriority {get;}。 但是,我想要一个计时器,如果AlertState变得Triggered并且LastAlertTime有一个有效的时间,它就会启动。 该计时器将在 30 秒后将AcknowledgementPriority设置为 1 . 如果AlertState在任何时间点变得NotTriggered,那么AcknowledgementPriority将再次变得0

我很确定我可以在"计时器"部分使用类似 Observable.From(1).Delay(Timespan.FromSeconds(30)) 的东西,但我正在努力使用 Rx 的方式来做到这一点。

谢谢。

我想你正在寻找这样的东西:

public class TestVm : ReactiveObject
{
    public enum Detection { NotTriggered, Triggered };
    readonly ObservableAsPropertyHelper<Detection> _alertState;
    public Detection AlertState => _alertState.Value;
    readonly ObservableAsPropertyHelper<DateTimeOffset> _lastAlertTime;
    public DateTimeOffset? LastAlertTime => _lastAlertTime.Value;
    readonly ObservableAsPropertyHelper<int> _acknowledgementPriority;
    public int AcknowledgementPriority => _acknowledgementPriority.Value;
    public TestVm()
    {
        this.WhenAnyValue(x => x.AlertState, x => x.LastAlertTime)
            .Where(t => t.Item2.HasValue)                               //If LastAlertTime has a valid time
            .Select(t => t.Item1 == Detection.Triggered                 //a timer that kicks off if AlertState becomes Triggered
                ? Observable.Return(1).Delay(TimeSpan.FromSeconds(30))  //Timer would after 30 seconds set AcknowledgementPriority to 1
                : Observable.Return(0)                                  //If AlertState becomes NotTriggered at any point in time then AcknowledgementPriority would become 0 again
            )
            .Switch()
            .StartWith(0)                                               //that returns 0 by default
            .ToProperty(this, x => x.AcknowledgementPriority, out _acknowledgementPriority);
    }
}

Switch是关键:它接收可观察量的可观察量,并"切换"到发出的最新可观察量。

相关内容

  • 没有找到相关文章

最新更新