Tuesday, 18 June 2013

Rx Operators - Basic stream filtering (Take,Skip, First, Last etc..)

Take

There are four overloads in all, the first one takes the specified number of contiguous elements, the second will take elements till the end of specified timespan. Other two overloads are taking IScheduler instance fro synchronization if required.



TakeLast, TakeLastBuffer, TakeUntil, TakeWhile

TakeLast will confuse many. Since observables are future collection, how will we know if we will reach the end of stream exactly after n elements. To explain this, in reality, TakeLast is delayed. This operator acumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence.

TakeLastBuffer behaves exactly the same. The only difference is that it returns a observable of list of source element i.e. the contents of the entire buffer upon reaching the end of stream. On the contrary TakeLast returns Observable of elements.


The following overload comes handy when we require to control the stream using some external functions:-

public static IObservable<TSource> TakeWhile<TSource>(this IObservable<TSource> source, Func<TSource, bool> predicate);



Skip

Similarly skip has got three overloads.


SkipLast, SkipUntil & SkipWhile

We also have following skip functions useful for filtering out elements from observable stream:-



First, FirstOrDefault, FirstAsync, FirstOrDefaultAsync

First returns the first element of an observable sequence, while FirstAsync returns the sequence containing the first element in the observable sequence.

FirstOrDefault returns the first element in the observable sequence, or a default value if no such element exists. FirstOrDefaultAsync returns the sequence containing  first element in the observable sequence, or a default value if no such element exists.


Last, LastOrDefault, LastAsync, LastOrDefaultAsync



Last returns the Last element of an observable sequence, while LastAsync returns the sequence containing the Last element in the observable sequence.

LastOrDefault returns the Last element in the observable sequence, or a default value if no such element exists. LastOrDefaultAsync returns the sequence containing  Last element in the observable sequence, or a default value if no such element exists.



No comments:

Post a Comment