Vladislav Sorokin
Vladislav Sorokin

Reputation: 9

Detect when property changed at any element in the list

I googled a lot and still not get an answer. The problem is very silly - I have collection of elements, and need to know when any property changed on any element. Not collection itself changed.

Pseudocode:

public class Item : ReactiveObject {
    [ObservableAsProperty]
    public bool PropertyToMonitor { get; }
}

public ReadOnlyObservableCollection<Item> Items;

So, how to get that any item in the Items list got PropertyToMonitor updated in observable manner?

Ugly workaround I use by now is:

Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
          .Subscribe(_ => InvokeAsync(StateHasChanged))

Spend a day and gave up after all.

UPD: resolved with quite straight solution, pseudocode:

public class UnitTest3 : ReactiveObject
{
    private readonly ITestOutputHelper _output;
    public class Item : ReactiveObject
    {
        [Reactive]
        public bool PropertyToMonitor { get; set; }
    }
    private ObservableCollection<Item> Items = new ObservableCollection<Item>();
    public UnitTest3(ITestOutputHelper output)
    {
        this._output = output;
    }
    [Fact]
    public void Test1()
    {
        bool signalled = false;
        var item = new Item { };
        Items.Add(new[] {item});
        Items.Select(s => s.WhenPropertyChanged(p => p.PropertyToMonitor).Select(v => v.Value))
             .Merge()
             .Subscribe(v =>
              {
                  _output.WriteLine("signalled: {0}", v);
                  signalled = v;
              });
        item.PropertyToMonitor = true;
        signalled.Should().BeTrue();
    }
}

Upvotes: 0

Views: 979

Answers (0)

Related Questions