Radin Gospodinov
Radin Gospodinov

Reputation: 2323

How to replace CreateDerivedCollection with dynamic data

I have the following code that converts the items from Items collection of wpf TabControl:

public IReadOnlyReactiveList<MyType> MyItems => base.Items.OfType<MyType>().CreateDerivedCollection(_ => _);

Both IReadOnlyReactiveList and CreateDerivedCollection extension are marked as obsolete.

base.Items collection is of type `ItemCollection`.

I don't know how to replace the call to CreateDerivedCollection with dynamic data and to preserve the functionality. MyItems list needs to be updated every time then the base Items collection is changed.

Upvotes: 1

Views: 869

Answers (1)

Glenn Watson
Glenn Watson

Reputation: 2888

This guide goes over how the conversion works https://reactiveui.net/docs/handbook/collections/

But to summarise.

public class MyClass
{
   private readonly ReadOnlyObservableCollection<MyType> _myItems;
   public MyClass()
   {
      base.Items
         // This makes a IObservable<IChangeSet<T>> which describes the changes
         .ToObservableChangeSet()
         // this will make sure you get the MyType
         .Filter(x => x is MyType)
         // This will convert them into MyType instances.
         .Transform(x => (MyType)x)
         // This is mostly only needed if your source allows multi threading
         .ObserveOn(RxApp.MainThreadScheduler)
         // This will make your _myItems keep in sync with what's done above
         .Bind(out _myItems)
         .Subscribe();
   }

   public ReadOnlyObservableCollection<MyType> MyItems => _myItems;
}

Worth a couple things noting.

DynamicData uses .NET types to expose to the outside world, such as ReadOnlyObservableCollection<T> rather than exposing their own types.

IObservable<IChangeSet<T>> (and IObservable<IChangeSet<TKey, TValue>>) are the two base observables you can create derived based functionality from. IObservable<IChangeSet>> indicates what has changed to a collection. The first time you use ToObservableChangeSet() it emits the current state of the collection.

SourceList<T>, SourceCache<TKey, TValue> are multithreaded aware and optimised to create IObservable<IChangeSet<T>> and IObservable<IChangeSet<TKey, TValue>>. Generally SourceList/SourceCache are meant to be private to your classes, and you expose using the Bind() method. You generate the change sets by using the Connect() method on them.

ObservableCollectionExtended is a good single threaded collection where you don't need to do derived based functionality.

Upvotes: 2

Related Questions