I know it's a good practice to encapsulate BehaviourSubjects in your services and fetch values with the Observable and set values with a setter.
But I wonder what kind of setter is prefered. There is the "old" way with a simple method called setExample(value) or the approach with set example(value). Are there any opinions and why?
Also when I need the current value from the BehaviourSubject in the coding, should I always use the Observable with a take(1) or is it okay to also have a getter with exampleSubject.getValue()?
import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class ExampleService {
private exampleSubject = new BehaviorSubject<string | null>(null)
example$ = this.exampleSubject.asObservable();
setExample(value: string | null) {
this.exampleSubject.next(value)
}
}
import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class ExampleService {
private exampleSubject = new BehaviorSubject<string | null>(null)
example$ = this.exampleSubject.asObservable();
set example(value: string | null) {
this.exampleSubject.next(value)
}
}