How to properly write complex observable logic is case of class inheritance?
Please check an example:
public class A : ReactiveObject
{
public A()
{
AProperty = new SimpleValue();
this.WhenAnyValue(x => x.AProperty)
// virtual method call in constructor
.Subscribe(x => CheckIsChanged());
// this will crash app because B is not initialized
AProperty.Value = true;
}
#region "AProperty" property
private SimpleValue _aProperty;
public SimpleValue AProperty
{
get { return _aProperty; }
set { this.RaiseAndSetIfChanged(ref _aProperty, value); }
}
#endregion
protected virtual bool CalculateIsChanged()
{
return AProperty.Value;
}
protected void CheckIsChanged()
{
IsChanged = CalculateIsChanged();
}
#region "IsChanged" property
private bool _isChanged;
public bool IsChanged
{
get { return _isChanged; }
set { this.RaiseAndSetIfChanged(ref _isChanged, value); }
}
#endregion
}
public class B : A
{
public B()
{
BProperty = new SimpleValue();
}
protected override bool CalculateIsChanged()
{
// crash will happen here
return BProperty.Value || base.CalculateIsChanged();
// definitely we can check BProperty for null
// but i hope there are more elegant way to do not call such methods before all class tree initialized
// or better way to write everything :)
}
#region "BProperty" property
private SimpleValue _bProperty;
public SimpleValue BProperty
{
get { return _bProperty; }
set { this.RaiseAndSetIfChanged(ref _bProperty, value); }
}
#endregion
}
public class SimpleValue: ReactiveObject
{
#region "Value" property
private bool _value;
public bool Value
{
get { return _value; }
set { this.RaiseAndSetIfChanged(ref _value, value); }
}
#endregion
}
This is simple example but dependencies and logic on the could be much harder (10 properties in each class to observe... complex logical decisions)
P.S. have no idea what to add to my "mostly code" question. Hope you find "more details" in the code comments.