Anonymous
Anonymous

Reputation: 1968

Observable class property doesn't trigger subscription

Simple observable variable works as expected an triggers callback immediately on the same thread. Why a class variable of any observable type (Subject, ISubject, Observable, IObservable) doesn't trigger callback?

Example with simple variable - [Works]

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

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

x1.OnNext("Hello");

Example with a class - [Does NOT work]

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");

Upvotes: 0

Views: 179

Answers (1)

Nenad
Nenad

Reputation: 26637

Problem is that you made Demo to return new instance of Subject<string> every time it is used.

Demo instance that you subscribed too, is not the same instance you called OnNext() on.

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

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

Keep it the same instance and it will work. For example:

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

or:

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

Upvotes: 2

Related Questions