反应性UI共享可观察逻辑

时间:2016-12-15 21:56:24

标签: reactiveui

如果不满足输入文本的cetain条件,我正在尝试设置特定的错误消息。

基本上如果输入网址为空,我想将ErrorHint设置为“服务器网址不能为空”

如果输入网址不是以https开头,则ErrorHint应为“服务器网址必须以https开头”

否则ErrorHint应为空字符串。

以下代码有效,但我觉得我正在复制我的可观测量中的逻辑。有更清洁的方法吗?

        // invalid if the server url is empty
        var serverUrlEmptyObservable =
            this.WhenAnyValue(x => x.NewServerUrl)
                .Where(string.IsNullOrWhiteSpace);

        // invalid if the url is not empty but does not start with https
        var serverUrlInvalidPrefixObservable =
            this.WhenAnyValue(x => x.NewServerUrl)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Where(x => !x.StartsWith(NewServerUrlRequiredPrefix));

        // valid if the server url is not empty and starts with proper prefix
        var validServerUrlObservable =
            this.WhenAnyValue(x => x.NewServerUrl)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Where(x => x.StartsWith(NewServerUrlRequiredPrefix));

        // set error message based on which observable fires
        ErrorHint = Observable.Merge(
            validServerUrlObservable.Select(x => ""), 
            serverUrlInvalidPrefixObservable.Select(x => $"Server URL must start with {NewServerUrlRequiredPrefix}"), 
            serverUrlEmptyObservable.Select(x => "Server URL cannot be empty"));

2 个答案:

答案 0 :(得分:1)

创建一个IObservable并使用ToProperty方法设置ErrorHint输出属性的值。这基本上是如何实现这种“ReactiveUI”方式:

public class ReactiveViewModel : ReactiveObject
{
    private const string NewServerUrlRequiredPrefix = "https";

    public ReactiveViewModel()
    {
        this.WhenAnyValue(x => x.NewServerUrl)
            .Select(_ =>
            {
                if (string.IsNullOrEmpty(NewServerUrl))
                    return "Server URL cannot be empty";
                else if (!NewServerUrl.StartsWith(NewServerUrlRequiredPrefix))
                    return $"Server URL must start with {NewServerUrlRequiredPrefix}";

                return string.Empty;
            }).ToProperty(this, x => x.ErrorHint, out _errorHint);
    }

    private string _newServerUrl;
    public string NewServerUrl
    {
        get { return _newServerUrl; }
        set { this.RaiseAndSetIfChanged(ref _newServerUrl, value); }
    }

    private readonly ObservableAsPropertyHelper<string> _errorHint;
    public string ErrorHint { get { return _errorHint.Value; } }
}

答案 1 :(得分:0)

您可以将所有逻辑放在一个UPDATE loc_state_journal SET state_journal_id = (state_journal_id - MOD(state_journal_id,1000))*100 + MOD(state_journal_id,1000) 函数中来组合:

Select

这只是将每个ErrorHint = this.WhenAnyValue(x => x.NewServerUrl) .Select(url => { if(string.IsNullOrWhiteSpace(url)) { return "Server URL cannot be empty"; } if(!url.StartsWith(NewServerUrlRequiredPrefix)) { return $"Server URL must start with {NewServerUrlRequiredPrefix}"; } return ""; }) .DistinctUntilChanged(); 值映射到适当的错误消息,然后仅在错误消息发生更改时通知观察者(使用NewServerUrl)。