Moran_bzh
Moran_bzh

Reputation: 49

Create one or multiple observables of a subject in a service?

According to the sources/sites consulted, we can see two approaches of creating a service with a subject/observable in order to share data :

  1. Initializing an observable of the subject and returning it (ONE observable of the subject)
export class TodoService {

    private _todo = new BehaviorSubject<any>([]);
    readonly todos$ = this._todo.asObservable();

    constructor() {}

    getTodos$() {
        return this.todos$;
    }
}
  1. Creating an observable of the subject each time we want to get the data (MULTIPLE observables of the subject)
export class TodoService {

    private _todo = new BehaviorSubject<any>([]);

    constructor() {}

    getTodos$() {
        return this._todo.asObservable();
    }
}

Which of those two approaches should be adopted ? What is the difference between them ?

Thank you

Upvotes: 0

Views: 1798

Answers (1)

Daniel Gimenez
Daniel Gimenez

Reputation: 20494

The only difference between the two is the first will only have one instance of an observable linked to the subject, whereas the second will create a new observable each time. There shouldn't be any practical differences.

I would use one of two alternative approaches depending on if it's actually important to hide the subject.

Subject Only

What are you accomplishing by hiding the subject? Does it really hurt anything if .next() is called externally? Unless there really is a good reason to hide it, I would make the subject read only and let consumers subscribe directly. I am biased towards this for any services I create that are exclusively used internally.

readonly todoSubject = new BehaviorSubject<any>([]);

Observable Field

If the subject must be hidden, then just use a read only field for the observable. Why do the todos$ have to be retrieved from a method? Unless there's some setup involved in there method, there is none. This is basically the same as your first example without the method.

private _todo = new BehaviorSubject<any>([]);
readonly todos$ = this._todo.asObservable();

Upvotes: 2

Related Questions