Frequently, in angular app, i have some service, which need to retreive some data through http request and share it to consumers through BehaviorSubject. It have implementation
What about initializing a stream in the constructor that is made hot by an initial call to getData
? Then the first result is cached in the ReplaySubject
class Service {
private init = new Subject();
private data = new ReplaySubject(1);
constructor() {
this.init.pipe(
take(1),
switchMap(() => anyHttpCall())
)
.subscribe(res => this.data.next(res));
}
getData() {
this.init.next();
return this.data.asObservable();
}
}