Building the log operator

We’ll build the log operator step by step. This will actually help you understand how to create your own operators. In fact, make me proud and create a utils/operators.ts file in your project. Now fill that thing with as much operators as you can. Your code will look FP-abulous.

A RxJS operator is a high order function. This means a function that returns another function.

2. The signature of the returned function is incomplete, though. The rule of thumb when building operators is: an RxJS operator must receive and return an observable. Let’s do it:

3. Too much trash, I came here to log stuff! We’ve been told since infancy that we need to subscribe to an observable to get its value. Therefore, if we want to log the incoming value, we need to subscribe to the input observable and call console.log.

…but look at dat green console.log though.

4. Now, keep in mind that the output observable will be the one which the next operator in line will subscribe to. Therefore, if we’re hijacking the source observable to log its values, then we must be responsible and pass the values over to the next operator. Think of it like a proxy that just gets the value, console.logs it and pass it over. We can achieve this by doing observer.next(val) .

5. Same principle applies for error and complete so, whenever our source errors or completes, our output will do too.

6. We need to be careful as we’re creating an inner subscription to the input source. Everybody has been told in a peer review to “handle dat subscription appropriately, you want memory leaks or what”. This situation is easily solved by following the official operator creation guideline which suggests to just return the inner subscription and forget about it. Let’s do that and see how our operator finally looks like:

Let it shine🕺

Time to use our brand new log operator.