Home > Back-end >  Should Observer be in constructor
Should Observer be in constructor

Time:03-07

I have an application that needs to send minor rxjs requests to reload certain methods in other components (components that are very much higher up in the navigation tree so inputs and outputs would be too messy). I have a child component which sends a boolean value to a service:

Child Component:

myMethod(){
 this.reloadComponentService.changeReload(true)
};

Reload Service:

import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs';

@Injectable()
export class ReloadComponentService {

    private _reloadSource = new BehaviorSubject<boolean>(false);
    reload$ = this._reloadSource.asObservable();

    constructor() { }

    changeReload(val) {
        this._reloadSource.next(val);
        this._reloadSource.next(false); //reset it
    }
}

And my very high level parent component which is listening for changes to this has the following code in it's constructor:

constructor(private _reloadComponentService: ReloadComponentService) {

        this.subscription1 = this._reloadComponentService.reload$
            .subscribe(
            response => {

                if ((response === true)) {
                    this.getUnreadMessageCount();
                }
            });
    }

My question is should the observer be in the constructor in the first place? I know it works but I've heard generally people don't like putting any code in the constructor because of runtime issues.

CodePudding user response:

You can place the subscription in ngOnInit. You should also not forget to unsubscribe; for example in ngOnDestroy.

CodePudding user response:

I don't know the rest of your code, but instead of subscribing, why don't you just use the async pipe in your template:

<span>Unread: {{ unreadMessageCount$ | async }}</span>
readonly unreadMessageCount$: Observable<number> = this.rcs.reload$.pipe(
  // only continue if response is truthy
  filter((response) => response),
  // connect to observable returned from getUnreadMessageCount
  switchMap(() => this.getUnreadMessageCount())
);

constructor(private rcs: ReloadComponentService) {}

This way you have no code inside your constructor (neater, there is no real difference in doing it in the ngOnInit), and you don't have to deal with subscribing and unsubscribing as this is handled inside the async pipe.

The filter operator only emits values that pass the provided condition. Where as the switchMap will map to another observable.

  • Related