Implement your own operator of for IObservable

  • 2021-12-12 09:31:09
  • OfStack

You can extend Rx by adding new operators for operations not provided by the LINQ library, or by creating your own standard query operator implementation to improve readability and performance. Writing a custom version of the standard LINQ operator is useful when you want to operate with in-memory objects and when you expect to customize a comprehensive view that does not require queries.

Create a new operator

LINQ provides a complete set of operators that cover most possible operations on a set of entities. However, you may need an operator to add specific semantics to the query, especially if you can reuse the operator multiple times in your code.

Many existing LINQ operators are actually built using other basic LINQ operators. For example, the SelectMany operator is constructed by combining the Select and Merge operators, as shown in the following code.


public static IObservable<TResult> SelectMany<TSource, TResult>( this IObservable<TSource> source, Func<TSource, IObservable<TResult>> selector) 
{ 
  return source.Select(selector).Merge(); 
} 
In t

By reusing the existing LINQ operator when building the new LINQ operator, you can take advantage of existing performance or exception handling capabilities implemented in the Rx library.

When writing custom operators, it is best not to leave any unused sex products; Otherwise, you may find that resources may actually be leaked, and cancellation may not work properly.

Customize existing operators

Adding new operators to LINQ is a way to extend its functions. However, you can also improve code readability by including existing operators into more specialized and meaningful operators.


Related articles: