Skip to content

Instantly share code, notes, and snippets.

@RolandPheasant
Created January 18, 2016 21:21
Show Gist options
  • Save RolandPheasant/65fc6240d31d2113108c to your computer and use it in GitHub Desktop.
Save RolandPheasant/65fc6240d31d2113108c to your computer and use it in GitHub Desktop.
public static class DynamicDataExtensions
{
public static IObservable<IChangeSet<TObj>> FilterOnProperty<TObj, TProp>(
this IObservable<IChangeSet<TObj>> source,
Expression<Func<TObj, TProp>> selectProp,
Func<TObj, bool> predicate) where TObj : INotifyPropertyChanged
{
return Observable.Create<IChangeSet<TObj>>(observer =>
{
//share the connection, otherwise the entire observable chain is duplicated
var shared = source.Publish();
//do not filter on initial value otherwise every object loaded will invoke a requery
var changed = source.WhenPropertyChanged(selectProp, false)
.Select(v => v.Sender);
//start with predicate to ensure filter on loaded
var changedMatchFunc = changed.Select(_ => predicate).StartWith(predicate);
// filter all in source, based on match funcs that update on prop change
var changedAndMatching = source.Filter(changedMatchFunc,FilterPolicy.CalculateDiffSet);
var publisher = changedAndMatching.SubscribeSafe(observer);
return new CompositeDisposable(publisher, shared.Connect());
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment