Last active
August 29, 2015 14:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MultipleAssignmentDisposable dis = new MultipleAssignmentDisposable();
can be swapped forSerialDisposable dis = new SerialDisposable();
and then your inner subject will be disposed as you switch inner sequences.