Search code examples
c#dynamic-datareactiveui

C# DynamicData and WhenPropertyChanged - skip initial value when collection is initialized


I have a simple code:

class ItemViewModel : ReactiveObject
{
    private string _name;
    private string _value;

    public ItemViewModel(string name, string value)
    {
        _name = name;
        _value = value;
    }

    public string Name
    {
        get => _name;
        set => this.RaiseAndSetIfChanged(ref _name, value);
    }

    public string Value
    {
        get => _value;
        set => this.RaiseAndSetIfChanged(ref _value, value);
    }
}

IObservable<IChangeSet<ItemViewModel>> changeSet = CreateChangeSet();

I want to react to any change of the Value property in any of the objects in change set, and do something with new value. I tried like this:

changeSet 
    .WhenPropertyChanged(x => x.Value)
    .DistinctUntilChanged()
    .Subscribe(value =>
    {
         // do sth with value
    });

but WhenPropertyChanged provides initial value for each item when collection is initialized and I want to avoid that. How can I do this?


Solution

  • You just need to set the notifyOnInitialValue parameter to false. It's true by default. I just tried in a sandbox console app as a sanity check, and it does indeed work as expected.

    changeSet
        .WhenPropertyChanged(x => x.Value, notifyOnInitialValue: false)
    

    Source: https://github.com/reactiveui/DynamicData/blob/63960b0fa7bd0362c40e137498cd0014ba02f3dc/src/DynamicData/Binding/NotifyPropertyChangedEx.cs#L59