2

I have a dashboard with dynamic widgets adding up, If a user adds two widgets which have same api call, it obviously hit two ajax call. How can I make sure, if the API is called once, the second call get the result of first one

1 Answers1

0

You can use the shareReplay operator. It is caching the results and emits them to new subscribers without creating the stream again.

import { ajax } from 'rxjs/ajax';
import { tap, map, shareReplay } from 'rxjs/operators';

const endpoint = 'https://api.github.com/users?per_page=1'

const obs$ = ajax.getJSON(endpoint).pipe(
  tap(() => console.log('Making BE call')),
  shareReplay(1)
);

obs$.subscribe(x => console.log('[1]', x));
obs$.subscribe(x => console.log('[2]', x));

// Output:
// Making BE call
// [1] object
// [2] object

You can have a look at this small demo: https://stackblitz.com/edit/rxjs-eyk9y5

Bene
  • 874
  • 1
  • 10
  • 15