Rx有BufferWithTime、BufferWithCount和BufferWithTimeOrCount的方法,我想写一个BufferWithPredicate方法,看起来是这样的:
public IObservable<IList<T>> BufferWithPredicate<T>(this IObservable<T> input, Func<T, IList<T>, bool> predicate)
从本质上讲,除非谓词返回false,否则将向现有缓冲区添加新项,在这种情况下,将返回缓冲区并启动新的缓冲区。谓词将下一个项和缓冲区作为参数。
我怎样才能做到这一点?
这应该为您完成。我正在使用Observable.Defer,以便它也能与冷的Observable一起工作:
public static class MyObservableExtensions
{
public static IObservable<IList<T>> BufferWithPredicate<T>(this IObservable<T> input, Func<T, IList<T>, bool> predicate)
{
return Observable.Defer(() =>
{
var result = new Subject<IList<T>>();
var list = new List<T>();
input.Subscribe(item =>
{
if (predicate(item, list))
{
list.Add(item);
}
else
{
result.OnNext(list);
list = new List<T>();
list.Add(item);
}
},
() => result.OnNext(list));
return result;
});
}
}
用法:
var observable = new[] { 2, 4, 6, 8, 10, 12, 13, 14, 15 }.ToObservable();
var result = observable.BufferWithPredicate((item, list) => item % 2 == 0);
result.Subscribe(l => Console.WriteLine("New list arrived. Count = {0}", l.Count));
输出:
"New list arrived. Count = 6"
"New list arrived. Count = 3"