Observable class 属性 不触发订阅

Observable class property doesn't trigger subscription

简单的可观察变量按预期工作,立即在同一线程上触发回调。 为什么任何可观察类型(Subject、ISubject、Observable、IObservable)的 class 变量不触发回调?

带有简单变量的示例 - [有效]

var x1 = new Subject<string>();
var x2 = x1.DistinctUntilChanged();

x2.Subscribe(o =>
{
  // Triggered as expected
});

x1.OnNext("Hello");

带有 class 的示例 - [不起作用]

public class InstrumentModel
{
  public Subject<string> Demo => new Subject<string>();
}

var class1 = new InstrumentModel();

class1.Demo
  //.DistinctUntilChanged()
  //.SubscribeOn(Scheduler.CurrentThread)
  //.ObserveOn(Scheduler.CurrentThread)
  .Subscribe(o =>
{
  // Never triggered 
});

class1.Demo.OnNext("Hello");

问题是每次使用 Subject<string> 时,您都创建了 Demo 到 return 个新实例。

Demo 您订阅的实例与您调用 OnNext() 的实例不同。

class1.Demo.Subscribe(...); // makes new instance `Subject<string>`

class1.Demo.OnNext("Hello"); // makes another new instance of `Subject<string>`

保持同一个实例,它将起作用。例如:

public class InstrumentModel
{
  public Subject<string> Demo = new Subject<string>();
}

或:

public class InstrumentModel
{
    public InstrumentModel()
    {
        this.Demo = new Subject<string>();
    }
    public Subject<string> Demo { get; }
}