1
\$\begingroup\$

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.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?

\$\endgroup\$
0
\$\begingroup\$

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);
      console.log('Payload: ', eventData);
      console.groupEnd();
    })
    .catch(error => {
      console.group();
      console.error('----- SOCKET INBOUND -----');
      console.error('Action: ', eventName);
      console.error('Error: ', error);
      console.groupEnd();
    });
}
\$\endgroup\$
  • 1
    \$\begingroup\$ I use '.do()' almost daily with ngrx/effects, can't believe I couldn't connect the dots :). Thanks tremendously for your help! \$\endgroup\$ – Andreas Johansson Jan 1 '18 at 2:14
  • \$\begingroup\$ @AndreasJohansson yeah, no problem. This happens to all of us time to time. \$\endgroup\$ – Igor Soloydenko Jan 1 '18 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.