Custom rxjs operatros

When working in Angular we are accustomed to working with observables and pipes in our day-to-day, but from time to time we are experiencing a lot of code duplication, we use the same operators in order to attain a similar UI and UX feel of our application.

Let’s use a search bar for our example since it is easy to understand and we know what to expect from the outcome.

if we had to write down the classic way it would look something like this:

This is probably the most common way to create the logic of a search input bar, and the simplest too.
We first use “debounceTime(500) ” in order to not emit on each keystroke but to emit once in 500 ms. Then we use distinctUntillChanged in order to not fire to emits of the same search value one after another. and then whatever logic we have can be done after. this ok and will work, but as your app grows you have more and more search bars with the exact same logic, so let’s make our own operator that will contain the logic.

Due to the fact that my operator returns type: OperatorFunction<any, any> I know that it will emit the value to our tap/map/concatmap.

we can now add some cool features to our operations such as a filter to “swallow” events that don’t fit our requirements, for our example I will use a minimum amount of chars.

The filter operator will not pass on values that don’t pass our requirement, which in this case is to pass only if the value is empty or more than 2 characters.

But wait… our next input needs more than 4 characters in order to search as expected. so now we need to add options to our operator.

In the image above we have set the ability to pass options, which has a key of minLength. If we pass the minLength key to it our filter will now check if the value is above 4 characters.

Creating custom RxJs operators should be a simple way to avoid code duplication and the ability to have ease of access to custom options, and to give your application an all-around similar feeling and expierence.