Update ReadOnlyObservableCollection created with DynamicData based on item's property

419 Views Asked by At

I have next class:

public class StateObject
{
   public bool IsEnabled { get; set; }
   public string Value { get; set; }
}

Later in code I have some source of object of this kind as an Observable, for example created via Observable.Interval.

var interval = TimeSpan.FromSeconds(1);
IObservable<StateObject> source = Observable.Interval(interval).Select(x => new StateObject { Value = "Test", IsEnabled = x % 2 == 0})

I need to bind this observable to ReadOnlyObservableCollection with taking into account IsEnabled property in such way which will either Add or Remove item from collection. So, if it is IsEnabled == true, it should be added, otherwise it should be removed if it is alreay in the collection.

I have tried following code to obtain what I need but couldn't make it removing items, only add them to collection.

private readonly ReadOnlyObservableCollection<string> _values;
public ReadOnlyObservableCollection<string> Values => _values;

source
      .ToObservableChangeSet()
      .Filter(x => x.IsEnabled)
      .Transform(x => x.Value)
      .Bind(out _values)
      .Subscribe();

I have another idea to make it working with a proxy SourceList from DynamicData, but I'm just wondering whether is it possible to achieve what I need without creating this proxy SourceList.

1

There are 1 best solutions below

1
On BEST ANSWER

Try to use the overload of ToObservableChangeSet that takes a key selector.

source
  .ToObservableChangeSet(x => x.Value)
  .Filter(x => x.IsEnabled)
  .Transform(x => x.Value)
  .Bind(out _values)      
  .Subscribe();

Seems to work for me.