'How can I use shareReplay in combineLatest?

I have components that use combineLatest heavily. For example, in one component I have:

const users$ = this.http.get<User[]>('URL');
const userAction$ = this.http.get<User>('Another Url');

combineLatest(
    this.userAction$,
    this.users$
)
.pipe(
    map(([users, action]) => {
        this.display(users, action);
    })
);   

The users$ = this.http.get<User[]>('URL'); is used in every component. So the HTTP requests are duplicated in every component.

For example, in another component I have similar code.

const users$ = this.http.get<User[]>('URL');
const flag$ = this.http.get<Flag>('Flag Url');

combineLatest(
    this.flag$,
    this.users$
)
.pipe(
    map(([users, flag]) => {
        this.setMap(users);
        this.extractFlag(flag); 
    })
);  

We also use the same users$ = this.http.get<User[]>('URL'); here.

I've tried using shareReplay like this:

users$ = this.http.get<User[]>('URL').pipe(shareReplay(1));

However it doesn't seem to work; I still can see multiple HTTP requests.

Update:

The above code is just a demo. Actually I use service to do that.

const flag$ = this.http.get<Flag>('Flag Url');

combineLatest(
    this.flag$,
    this.apiService.users$
)
.pipe(
    map(([users, flag]) => {
        this.setMap(users);
        this.extractFlag(flag); 
    })
);  

I api.service, I have

public users$ = (): Observable<User[]> => {
   return this.http.get<User[]>('URL').pipe(shareReplay(1));
}


Solution 1:[1]

Change

public users$ = (): Observable<User[]> => {
   return this.http.get<User[]>('URL').pipe(shareReplay(1));
}

to

private _users$ = this.http.get<User[]>('URL').pipe(shareReplay(1));
public users$ = (): Observable<User[]> => _users$;

The public users$ function is redundant, but we'll keep it here so you don't have the change the public API of your service when testing this. I think this should work :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mrk Sef