2017-04-03 42 views
0

我有一個視圖模型有以下幾點:發出值只有當某些條件得到滿足,否則發出另一個vlaue

enum Detection {NotTriggered, Triggered};

public Detection AlertState => _alertState.Value;

public DateTimeOffset? LastAlertTime => _lastAlertTime.Value;

我想怎麼辦有另一個屬性:int AcknowledgementPriority {get;}默認情況下返回0。不過,如果AlertState變成Triggered,並且LastAlertTime有效時間,我想要一個計時器。該計時器在30秒後將AcknowledgementPriority設置爲1。如果AlertState在任何時間點變爲NotTriggered,則AcknowledgementPriority將再次變爲0

我很確定我可以使用像Observable.From(1).Delay(Timespan.FromSeconds(30))這樣的「計時器」部分,但我正在努力與Rx的方式做到這一點。

謝謝。

回答

1

我認爲你在尋找這樣的事情:

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的關鍵在於:它發生在可觀察到的觀測量和「開關」的最新觀測到發射。

相關問題