# Logging observable values while extending service

I'm trying to extend a service function which returns an Observable<T>. The idea is to extend the function so I can add logging functionality whenever the observable emits a new value.

fromEvent<T>(eventName: string): Observable<T> {
super.fromEvent(eventName).subscribe(
function next(data) {
console.group();
console.log('----- SOCKET INBOUND -----');
console.log('Action: ', eventName);
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():

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

fromEvent<T>(eventName: string): Observable<T> {
return super
.fromEvent(eventName)
.do(eventData => {
console.group();
console.log('----- SOCKET INBOUND -----');
console.log('Action: ', eventName);