ReactiveProperty初始值

时间:2017-11-16 22:17:01

标签: c# xamarin mvvm reactive-property

我正在尝试将初始值设置为public ReactiveProperty<string> ConnectionStatus

public ViewModelConstructor()
{
    ConnectionStatus = Observable
                    .Interval(RefreshInterval)
                    .Select(x => Observable.FromAsync(() => networkDiscovererService.CanDiscoverAsync("192.168.1.1", RequestTimeout)))
                    .Concat()
                    .Select(isConnected => isConnected ? $"connected" : $"not connected")
                    .ToReactiveProperty();
}

即使我试图像这样实例化它

public ReactiveProperty<string> ConnectionStatus { get; } =
            new ReactiveProperty<string>("Checking connectivity...");

在观察者返回某些内容之前,它仍然是空的。

有什么想法吗?我正在使用此library

1 个答案:

答案 0 :(得分:1)

使用ReactiveProperty ctor获取订阅的初始值(如behaviorSubject或Replay(1)):

    [Test]
    public void ShouldReturnAValuOnSubscribe()
    {
        var testScheduler = new TestScheduler();
        var testableObserver = testScheduler.CreateObserver<int>();

        var reactiveProperty = new ReactiveProperty<int>(30);
        reactiveProperty.Subscribe(testableObserver);

        Assert.AreEqual(30, testableObserver.Messages.Single().Value.Value);
    }

使用.ToReactiveProperty()获取订阅的初始值(如behaviorSubject或Replay(1)):

    [Test]
    public void ShouldReturnAValuOnToReactiveProperty()
    {
        var testScheduler = new TestScheduler();
        var testableObserver = testScheduler.CreateObserver<int>();

        var reactiveProperty = Observable.Never<int>().ToReactiveProperty(40);
        reactiveProperty.Subscribe(testableObserver);

        Assert.AreEqual(40, testableObserver.Messages.Single().Value.Value);
    }

不要在订阅上获得初始值 - 更改ReactivePropertyMode:

    [Test]
    public void ShouldNotReturnAnInitialValue_WhenModeIsNone_AndOnSubscribe()
    {
        var testScheduler = new TestScheduler();
        var testableObserver = testScheduler.CreateObserver<int>();

        var reactiveProperty = new ReactiveProperty<int>(30, ReactivePropertyMode.None);
        reactiveProperty.Subscribe(testableObserver);

        Assert.IsEmpty(testableObserver.Messages);
    }

基本上,您要找的是初始值 ReactivePropertyMode.RaiseLatestValueOnSubscribe 标志。

在第一种情况下,您忘记使用初始值提供ToReactiveProperty()(例如ToReactiveProperty(30))

它应该在第二种情况下适用于你 - 默认情况下模式设置为 ReactivePropertyMode.RaiseLatestValueOnSubscribe (检查ShouldReturnAValuOnSubscribe)。尝试明确设置模式(例如 ShouldNotReturnAnInitialValue_WhenModeIsNone_AndOnSubscribe )。

我使用了ReactiveProperty 3.6.0。

顺便说一句,基于计时器测试连接并不是一个好主意:)