Logging observable values while extending service I'm trying to extend a service function which returns an Observable&lt;T&gt;. The idea is to extend the function so I can add logging functionality whenever the observable emits a new value.

fromEvent&lt;T&gt;(eventName: string): Observable&lt;T&gt; {
    super.fromEvent(eventName).subscribe(
        function next(data) {
            console.group();
                console.log('----- SOCKET INBOUND -----');
                console.log('Action: ', eventName);
                console.log('Payload: ', data);
            console.groupEnd();
        }
    );

    return super.fromEvent(eventName);


How can I make my function more effective? Because whenever fromEvent() is invoked a subscription is created and an observable is returned from the base class. As I understand, all subscriptions should at some point be unsubscribed.

Or are there any other way you could implement a logging functionality on an observable that listens to a specific event?
One way to achieve what you want is to use .do() and may be .catch() operators.

.do() operator taps on a target stream and executes a function on each non-error event in the stream. It is designed specifically for this purpose, which you can define more generically as side effects:


  This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. -- RxJs docs


Notice that .do():


does NOT affect the original Observable stream in any way. This function itself returns an Observable of the same type as the original one. 
does NOT subscribe to the original Observable, so the .subscribe() invocation is required down the road.
does NOT react to error events in the original Observable. Therefore, you may want to use .catch() to log the errors.




fromEvent&lt;T&gt;(eventName: string): Observable&lt;T&gt; {
  return super
    .fromEvent(eventName)
    .do(eventData =&gt; {
      console.group();
      console.log('----- SOCKET INBOUND -----');
      console.log('Action: ', eventName);
      console.log('Payload: ', eventData);
      console.groupEnd();
    })
    .catch(error =&gt; {
      console.group();
      console.error('----- SOCKET INBOUND -----');
      console.error('Action: ', eventName);
      console.error('Error: ', error);
      console.groupEnd();
    });
}