开发者

ReactiveExtensions BufferWithPredicate

Rx has methods for BufferWithTime, BufferWithCount and BufferWithTimeOrCount, I want to write a BufferWithPredicate method, which would look like so:

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

Essentially, new items will be added to the existing buffer, unless the predicate returns false, in which case the buffer will be returned and a new one will be started. The predicate takes the next item, and the buffer so far as parameters.

How can I 开发者_JAVA百科achieve this?


This should do it for you. I'm using Observable.Defer so that it works with cold observables as well:

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;
            });
    }
}

Usage:

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));

Output:

"New list arrived. Count = 6" 
"New list arrived. Count = 3"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜