我想要一个每次密钥更改时都会发出新的observable的GroupBy。有这样的事吗?
像这样的伪代码:
[1,3,5,2,4,3,7] groupByConsecutive? oddEven
会产生
Observable[Observable[1,3,5],Observable[2,4],Observable[3,7]]
答案 0 :(得分:1)
我花了一些时间想出一些不依赖于Subject
的东西,但我认为这会做你想做的事情:
new int[] { 1, 3, 5, 2, 4, 3, 7 }
.ToObservable()
.Publish(let =>
let
.GroupByUntil(
x => x % 2,
group => let.SkipWhile(x => x % 2 == group.Key)))
您可以将上述内容重构为更常规的扩展方法,如下所示:
public static class EnumerableExtensions
{
public static IObservable<IGroupedObservable<TKey, TSource>> GroupByUntilChanged<TSource, TKey>(
this IObservable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer = null)
{
comparer = comparer ?? EqualityComparer<TKey>.Default;
return
source
.Publish(let =>
let
.GroupByUntil(
keySelector,
group => let.SkipWhile(x => comparer.Equals(keySelector(x), group.Key))));
}
}
然后这样称呼它:
new int[] { 1, 3, 5, 2, 4, 3, 7 }
.ToObservable()
.GroupByUntilChanged(x => x % 2)