简单的可观察变量按预期工作,并在同一线程上立即触发回调。为什么任何可观察类型的类变量(Subject、ISubject、observable、IOobservable(都不会触发回调?
带有简单变量的示例-[Works]
var x1 = new Subject<string>();
var x2 = x1.DistinctUntilChanged();
x2.Subscribe(o =>
{
// Triggered as expected
});
x1.OnNext("Hello");
类的示例-[不工作]
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");
问题是您使Demo
在每次使用时都返回Subject<string>
的新实例。
您也订阅的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; }
}