shareReplay: can I reset or set the buffer size to 0 so that new subriptions have to wait for a new emit

Viewed 616

I have the following observable:

this.roles$ = auth.User$
            .pipe(tap((val: JwtUser|null) => this.logger.debug('Session updated, updating permissions %o', val)))
            .pipe(switchMap(this.getRoles.bind(this)))
            .pipe(shareReplay({refCount: true, bufferSize: 1}));

The getRoles() method performs a HTTP request every time the User$ emits. The last fetched value is replayed to all new subscriptions. When the User$ emits, however, I do not want subscriptions to get the last value. Instead, I want them to wait for the newly fetched one. I thought I could achieve this by resetting/clearing the buffer whenever User$ emits, but I can't figure out how to do this. Is there an other approach I could try or a way to achieve this one?

Thanks!

1 Answers

If I understand correct, you actually like a buffer size of 0. However, shareReplay(0) emits the last value of the source like shareReplay(1) does (see this explanation of shareReplay). You can use share and a dummy subscriber instead:

this.roles$ = auth.User$
            .pipe(tap((val: JwtUser|null) => this.logger.debug('Session updated, updating permissions %o', val)))
            .pipe(switchMap(this.getRoles.bind(this)))
            .pipe(share());
// keep `refCount` above 0 using a dummy subscription
this.roles$.subscribe(() => {});

Please let me know via a comment if this meets your requirements.

Related