使用异步扩展方法时,观察到的订阅不会触发

时间:2019-07-05 13:14:11

标签: c# wpf system.reactive reactiveui rx.net

对于一个新项目,我正在使用ReactiveUI。我开始非常喜欢反应式编程背后的想法,但是仍然难以解决一些概念和编写惯用代码的问题。

在此示例中,我有一个非常基本的MainWindow,带有一个名为“ UserId”的文本框:

<Window
    x:Class="ReactiveUiDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"
    Width="800"
    Height="450">
    <StackPanel>
        <TextBox x:Name="UserId" />
    </StackPanel>
</Window>

TextBox绑定到MainWindow的构造函数中相应视图模型上的属性:

using System.Reactive.Disposables;
using System.Windows;
using ReactiveUI;

namespace ReactiveUiDemo
{
    public partial class MainWindow : Window, IViewFor<MainWindowViewModel>
    {
        public MainWindowViewModel ViewModel { get; set; }

        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (MainWindowViewModel)value;
        }

        public MainWindow()
        {
            InitializeComponent();
            ViewModel = new MainWindowViewModel();

            this.WhenActivated(disposables =>
            {
                this
                    .Bind(ViewModel, vm => vm.UserId, v => v.UserId.Text)
                    .DisposeWith(disposables);
            });
        }
    }
}

此后的ViewModel将观察该属性(将ReactiveUI.Fody [Reactive]属性应用到该属性)。输入4位数字后,它将尝试查找用户,如果UserId为1234,则该用户成功或失败。然后使用MessageBox显示此结果。

using System;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;

namespace ReactiveUiDemo
{
    public sealed class MainWindowViewModel : ReactiveObject
    {
        [Reactive]
        public string UserId { get; private set; }

        public MainWindowViewModel()
        {
            this
                .WhenAnyValue(t => t.UserId)
                .Where(u => (u?.Length ?? 0) == 4)
                .Where(u => int.TryParse(u, out _))
                .Select(i => int.Parse(i))
                .Select(i => GetUserName(i))
                .Match(
                    userName => DisplaySuccess(userName),
                    failure => DisplayError(failure))
                .Do(_ => UserId = string.Empty)
                .Subscribe(
                    _ => MessageBox.Show("OnNext"),
                    _ => MessageBox.Show("OnError"),
                    () => MessageBox.Show("OnCompleted"));
        }

        private enum Failure { UserNotFound }

        private Result<string, Failure> GetUserName(int userId)
        {
            if (userId == 1234)
                return "Waldo";

            return Failure.UserNotFound;
        }

        private async Task<Unit> DisplayError(Failure failure)
        {
            MessageBox.Show($"Error: {failure}.");
            await Task.CompletedTask;

            return Unit.Default;
        }

        private async Task<Unit> DisplaySuccess(string userName)
        {
            MessageBox.Show($"Found {userName}!");
            await Task.CompletedTask;

            return Unit.Default;
        }
    }
}

“结果”类(或此结果的剥离版本)包含TSuccess或TFailure:

using System;

namespace ReactiveUiDemo
{
    public sealed class Result<TSuccess, TFailure>
    {
        private readonly bool _isSuccess;
        private readonly TSuccess _success;
        private readonly TFailure _failure;

        private Result(TSuccess value)
        {
            _isSuccess = true;
            _success = value;
            _failure = default;
        }

        private Result(TFailure value)
        {
            _isSuccess = false;
            _success = default;
            _failure = value;
        }

        public TResult Match<TResult>(Func<TSuccess, TResult> successFunc, Func<TFailure, TResult> failureFunc)
            => _isSuccess ? successFunc(_success) : failureFunc(_failure);

        public static implicit operator Result<TSuccess, TFailure>(TSuccess value)
            => new Result<TSuccess, TFailure>(value);

        public static implicit operator Result<TSuccess, TFailure>(TFailure value)
            => new Result<TSuccess, TFailure>(value);
    }
}

让我头疼的扩展方法是Match方法,其定义如下:

using System;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;

namespace ReactiveUiDemo
{
    public static class ObservableExtensions
    {
        public static IObservable<TResult> Match<TSuccess, TFailure, TResult>(
            this IObservable<Result<TSuccess, TFailure>> source,
            Func<TSuccess, Task<TResult>> success,
            Func<TFailure, Task<TResult>> failure)
            => Observable.FromAsync(async () => await source.SelectMany(result => result.Match(success, failure).ToObservable()));
    }
}

在Match扩展方法之前,代码将按预期工作。 DisplayError或DisplaySuccess被调用,但这已经结束了。 Do和Subscribe中的操作未执行。我相信我的Match扩展方法存在问题,但我不知道如何解决。

作为旁注,我想有一种更好的方式来编写此位:

                .Where(u => (u?.Length ?? 0) == 4)
                .Where(u => int.TryParse(u, out _))
                .Select(int.Parse)

我可以想象使用TryParseInt扩展方法,但是也许不需要它吗?

修改

根据@GlennWatson的回答更新了扩展方法,它现在可以正常运行了:

public static IObservable<TResult> Match<TSuccess, TFailure, TResult>(
    this IObservable<Result<TSuccess, TFailure>> source,
    Func<TSuccess, Task<TResult>> success,
    Func<TFailure, Task<TResult>> failure)
    => source.SelectMany(r => r.Match(success, failure).ToObservable());

1 个答案:

答案 0 :(得分:1)

FromAsync()方法仅用于基于任务的系统。

在使用Observable和后续的Linq样式方法时,请尝试使其尽可能保持Observable形式。

在您的示例中,您正在等待一个Observable并将其包装在FromAsync中。 SelectMany有一个重载,它了解基于任务的操作。