Skip to content

Instantly share code, notes, and snippets.

@Dorus
Last active August 29, 2015 14:25
Show Gist options
  • Save Dorus/6fc7a44e02859eae05fe to your computer and use it in GitHub Desktop.
Save Dorus/6fc7a44e02859eae05fe to your computer and use it in GitHub Desktop.
GroupBy that closes and creates a new Group when the key changes. Useful on sorted collections.
public static IObservable<IObservable<TElement>> GroupByDistinct<TElement, TKey>(this IObservable<TElement> source, Func<TElement, TKey> keySelector)
{
return Observable.Create<IObservable<TElement>>(o =>
{
SerialDisposable dis = new SerialDisposable();
Subject<TElement> sub = new Subject<TElement>();
dis.Disposable = sub;
o.OnNext(sub.AsObservable());
bool first = true;
TKey prev = default(TKey);
return new CompositeDisposable(source.Subscribe(el =>
{
TKey cur = keySelector(el);
if (first)
{
first = false;
prev = cur;
}
else if (!cur.Equals(prev))
{
sub.OnCompleted();
sub = new Subject<TElement>();
dis.Disposable = sub;
o.OnNext(sub.AsObservable());
prev = cur;
}
sub.OnNext(el);
}, er =>
{
sub.OnCompleted();
o.OnError(er);
}
, () =>
{
sub.OnCompleted();
o.OnCompleted();
}
), dis);
});
}
@LeeCampbell
Copy link

MultipleAssignmentDisposable dis = new MultipleAssignmentDisposable(); can be swapped for SerialDisposable dis = new SerialDisposable(); and then your inner subject will be disposed as you switch inner sequences.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment