建议使OAPH支持的输出属性像普通属性一样工作吗?

时间:2017-06-06 04:05:50

标签: reactiveui

问题:我根据您的文档建议使用OAPH设置了属性。但是因为OAPH使用UI线程观察,取决于引用属性的哪个线程,属性may not behave like a normal property(即getter函数)。它不会立即根据您提供的getter功能代码提供更新值。相反,它返回一个缓存的值(如果你在正确的线程上,这不是一个问题)。我认为这在某种程度上有利于UI响应。

class Rectangle
{
    private int _height;
    public int Height { get => _height; set => this.RaiseAndSetIfChanged(ref _height, value); }

    private int _width;
    public int Width { get => _width; set => this.RaiseAndSetIfChanged(ref _width, value); }

    readonly ObservableAsPropertyHelper<bool> _isSquare;
    public bool IsSquare => _isSquare.Value;

    public Rectangle
    {
        /**/
        _isSquare = this.WhenAnyValue(
                        This => This.Width,
                        This => This.Height,
                        (h,w) => (h == w))
                        .ToProperty(this, This => This.IsSquare);
        /**/
    }

    void SetHeightAndWidthToTwo()
    {
        Height = 2;
        Width = 2;
        // Width and Height have been updated and PropertyChanged
        // notifications have been raised by each. But if we're not
        // in the UI thread, IsSquare might not update immediately,
        // so this fails.
        Debug.Assert(IsSquare);
    }
}

但是,我希望我的VM代码中的属性能够像普通属性一样运行。建议的方法是什么?我可以在这里想到三个选择。

选项1:在制作OAPH时使用ImmediateScheduler

// In ctor:
_isSquare = this.WhenAnyValue(
    This => This.Width,
    This => This.Height,
    (h,w) => (h == w))
    .ToProperty(this, This => This.IsSquare, scheduler:ImmediateScheduler.Instance);

选项2:做一个&#34;正常&#34;财产以及输出财产。这导致简单的计算执行两次,但我想这是n.b.d.与选择ReactiveUI的调度以避免的与UI相关的计算浪费相比。

public bool IsSquare => (Height == Width);
readonly ObservableAsPropertyHelper<bool> _isSquareOutput;
public bool IsSquareOutput => _isSquareOutput.Value;

// in ctor:
_isSquareOutput = this.WhenAnyValue(
    This => This.Width,
    This => This.Height,
    (h,w) => this.IsSquare)
    .ToProperty(this, This => This.IsSquareOutput);

选项3:进行自定义OAPH,允许我等待所选的Scheduler更新Value字段。我不是Rxpert,所以如果这是一个好主意,我想知道如何去做。

readonly ObservableAsPropertyHelper<bool> _isSquare;
public bool IsSquare => _isSquare.WaitForValue(); // ??

0 个答案:

没有答案