Is there a way to create an Observable-like object that calls a webservice only once and shares the result with all subscribers, whether they subscribe before or after the call?
Using a Subject
would provide the result to subscribers who subscribed before the call, not after.
const s: Subject<number> = new Subject();
s.next(1);
s.subscribe(x => {console.log(x)}); // will not print anything
A BehaviourSubject
requires an initial dummy value, which means subscribers who signed up before the call will receive this placeholder value instead of the actual result.
const s: BehaviorSubject<number> = new BehaviorSubject(123);
s.subscribe(x => {console.log(x)}); // will print dummy value 123, then 1
s.next(1);
I attempted to create my own custom Observable
, but encountered the issue of potentially calling the webservice multiple times.
let val: number|undefined = undefined;
const s = new Observable((observer) => {
if (val !== undefined) {
observer.next(val);
} else {
doMyHttpCall().subscribe({
response => {
this.val = 1;
observer.next(val);
});
}
});
s.subscribe(x => {console.log(x)});
s.subscribe(x => {console.log(x)}); // two clients may give two calls
What is the correct approach to achieve this functionality?