首页 > 解决方案 > 这种方法在 ReactiveUI 中是惯用的吗?

问题描述

我是 ReactiveUI 的新手,我试图尽可能地遵循它的精神和概念。我突然想到我可能误用了这种Subscribe方法。这是我的代码:它是登录屏幕的视图模型。

public class LoginViewModel : ReactiveObject
{
    [Reactive]
    public string Username { get; set; }

    [Reactive]
    public string Password { get; set; }

    public LoginResult LoginResult { [ObservableAsProperty] get; } = LoginResult.Unknown;

    public ReactiveCommand<Unit, LoginResult> LoginCommand { get; }

    private readonly IAuthenticationService m_authenticationService = null;
    private readonly INavigationService m_navigationService = null;

    public LoginViewModel(IAuthenticationService i_authenticationService, INavigationService i_navigationService,
        IScheduler i_mainThreadScheduler = null, IScheduler i_currentThreadScheduler = null)
        : base(i_mainThreadScheduler, i_currentThreadScheduler)
    {
        m_authenticationService = i_authenticationService;
        m_navigationService = i_navigationService;

        IObservable<bool> canLogin = this.WhenAnyValue(vm => vm.Username, vm => vm.Password,
                (username, password) => !string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
            .DistinctUntilChanged();

        LoginCommand = ReactiveCommand.CreateFromTask(Login, canLogin, null);
        LoginCommand.ToPropertyEx(this, vm => vm.LoginResult, scheduler: null);

        // This is where I'm not sure
        LoginCommand.Subscribe(lr => 
            {
                if (lr == LoginResult.Success)
                {
                    m_navigationService.NavigateToViewModel<HomeViewModel>();
                }
            });
    }

    private async Task<LoginResult> Login()
    {
        return await m_authenticationService.LogUserInAsync(Username, Password);
    }

(我已经定义了一个导航服务,因为我将使用 Xamarin.Android 和 Xamarin.iOS,所以我使用的是视图优先导航,它将在特定于平台的类中实现。无论如何,重要的部分是也就是说,如果登录成功,我想做一些事情(转到主屏幕)。)

我想知道Subscribe我调用的结果LoginCommand是否是惯用的方式。我可能应该在Login方法本身中实现这部分。另一方面,我喜欢将正确的登录及其结果与“下一步做什么”分开,并且Subscribe似乎正是:“命令完成后做什么”。

我的代码正确吗?或者那Subscribe是代码的味道,我应该以不同的方式做事?

标签: c#reactiveui

解决方案


推荐阅读