ReactiveUI Goodies–IReactiveDerivedList Filtering 1

In my last post Reactive Goodies–IReactiveDerivedList Basics I introduced IReactiveDerivedList and CreateDerivedCollection()  respectively. Based on the outlined example I would like to show how to use a derived list to apply filtering easily. To demonstrate an interactive behavior, I have added a new ViewModel property and UI element to our little Todo Demo App.

private bool _showTodoOnly;
 
public bool ShowTodoOnly
{
    get { return _showTodoOnly; }
    set { this.RaiseAndSetIfChanged(ref _showTodoOnly, value); }
}

The property ShowTodoOnly indicates whether the list only shows open Todo items or all of them. With a the addition of a parameter when calling CreateDerivedCollection() we can apply filtering to the root list in form of an lambda expression. If ShowTodoOnly is set to true we also check whether a Todo item is not done yet.

Items = _rootList.CreateDerivedCollection(x => x,
                                  x => !ShowTodoOnly || x.Done == false, 
                                  (x, y) => x.DueDate.CompareTo(y.DueDate));

While this filters our items on start-up correctly and as new items come in, we also want to switch the ShowTodoOnly at runtime. Unfortunately, there is no way to trigger a re-evaluation of the provided filter function. However, we can recreate the derived list whenever the ShowTodoOnly property changes.

this.ObservableForProperty(x => x.ShowTodoOnly)
            .Subscribe(_ =>
            {
              Items = _rootList.CreateDerivedCollection(x => x, 
                                       x => !ShowTodoOnly || x.Done == false, 
                                       (x, y) => x.DueDate.CompareTo(y.DueDate));
             });

This little example shows how easily we exercise filtering with the help of CreateDerivedCollection(). While this code works just fine it has some shortcomings. Since we re-create the derived collection whenever the ShowTodoOnly option changes, the ListView resets and we also lose all of the nice transition animations of the ListView. In my next post I will explore how we can improve the filtering scenario.

In the mean time you can find the code here https://github.com/bitdisaster/practicalcode

Happy Coding!

2 thoughts on “ReactiveUI Goodies–IReactiveDerivedList Filtering 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s