Reputation: 49
According to the sources/sites consulted, we can see two approaches of creating a service with a subject/observable in order to share data :
export class TodoService {
private _todo = new BehaviorSubject<any>([]);
readonly todos$ = this._todo.asObservable();
constructor() {}
getTodos$() {
return this.todos$;
}
}
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
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