ReactiveExtensions BufferWithPredicate

时间:2011-05-28 19:31:24

标签: c# system.reactive

Rx有 BufferWithTime BufferWithCount BufferWithTimeOrCount 的方法,我想写一个BufferWithPredicate方法,看起来像这样:

public IObservable<IList<T>> BufferWithPredicate<T>(this IObservable<T> input, Func<T, IList<T>, bool> predicate)

本质上,新项目将被添加到现有缓冲区,除非谓词返回false,在这种情况下将返回缓冲区并启动一个新缓冲区。谓词采用下一个项目,缓冲区为参数。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

这应该为你做。我正在使用Observable.Defer,以便它也适用于冷可观察量:

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"