我正在使用反應式UI,我想在完成一個過程後顯示一條消息,並在一段時間(4秒)後隱藏此消息。如果消息比隱藏時間快,則應重置超時,以便在最後一條消息顯示/更新後的4秒後始終隱藏消息。如果最後一條消息與之前的消息相同,則隱藏時間也應該延長。RxUI.NET - 在一段時間後隱藏消息
目前我有這個代碼,這是我想要的,但它看起來太麻煩了。我只是在試用RxUI,所以大部分時間我都不知道自己在做什麼。有沒有更好的方法來實現這個目標?
public class MainViewModel: ReactiveObject
{
// Message to be shown.
private string message;
public string Message { get => message; set => this.RaiseAndSetIfChanged(ref message, value);
// Flag for the UI, if the message panel should be visible.
private ObservableAsPropertyHelper<bool> isMessageVisible;
public bool IsMessageVisible => isMessageVisible.Value;
// Command that runs async process, the result is the message to be shown.
public ReactiveCommand<Unit, string> Run { get; private set; }
public MainViewModel()
{
var msg = this.WhenAnyValue(x => x.Message, x => !string.IsNullOrEmpty(x));
// If message changes, after 4 seconds return false, causing hiding the message panel.
var hide = msg.Select(x => false).Throttle(TimeSpan.FromSeconds(4), RxApp.MainThreadScheduler);
// Merge both sequences into one output property.
Observable.Merge(msg, hide).ToProperty(this, x => x.IsMessageVisible, out isMessageVisible);
Run = ReactiveCommand.CreateFromObservable(() => Observable.StartAsync(Process));
// Merge various message sources and set message property. Set Message = null to force property change.
Observable.Merge(Run, Run.ThrownExceptions.Select(x => x.Message)).Subscribe(x => { Message = null; Message = x; });
}
...
}
很好的答案。似乎人們必須徹底改變心態才能在Rx/UI中發揮作用。謝謝。 –