Rx.NET:这个.WhenAnyValue (x =比;x.Foo)在构造函数中抛出ArgumentNullExcep

本文关键字:构造函数 ArgumentNullExcep Foo 这个 NET WhenAnyValue Rx | 更新日期: 2023-09-27 18:11:10

我有一个类,我正在做类似于下面的事情:

public class Foo : ReactiveObject
{
    // The constructor that sets up a subscription
    public Foo()
    {
        this.WhenAnyValue(foo => foo.Bar)
            .Where(bar => bar != null)
            .Subscribe(bar => ...);
    }
    // Reactive property
    private IBar _bar;
    public IBar Bar
    {
        get { return _bar; }
        set { this.RaiseAndSetIfChanged(ref _bar, value); }
    }
}
现在,在构造实例时,我得到以下错误:
System.ArgumentNullException: Value cannot be null.
Parameter name: dispatcher
   at System.Reactive.Concurrency.CoreDispatcherScheduler..ctor(CoreDispatcher dispatcher)}

为了确保我没有对我的实例做一些愚蠢的事情,我把订阅分成了几个部分,只是为了测试:

var observable = this.WhenAnyValue(foo => foo.Bar); // <-- throws already on this line!
var nonulls = observable.Where(bar => bar != null);
var subscription = nonulls.Subscribe(bar => ...);

我找不到更好的方法来了解这里出了什么问题。如何获得有关此错误的更多信息?我怎么修理它?

Rx.NET:这个.WhenAnyValue (x =比;x.Foo)在构造函数中抛出ArgumentNullExcep

为了完整起见,我将从注释中提取一个答案:

当您开始观察您的属性时,似乎还没有创建CoreDispatcherScheduler。根据我的经验,当你在构造函数中使用可观察对象时,这些事情往往会发生,然后可能在应用程序生命周期的早期使用它们。

因此,将实例化移动到OnLaunched事件,而不是应用程序启动,可能会有所帮助。在可能的情况下,我尝试使用Init()函数而不是构造函数来连接我的可观察对象。