How to prevent multiple fetch calling in RxJS?

Viewed 373

I have the following code:

const fetchBook = (bookId: number) => {
    const title = 'Book' + bookId;
    console.log('fetch book:', title)
    // mimic http request
    return timer(200).pipe(mapTo({ bookId, title }));
}

const bookId$ = new Subject<number>();

const book$ = bookId$.pipe(
    mergeMap(bookId => fetchBook(bookId))
);

book$.subscribe(book => console.log('subscriber1: ', book.title))
book$.subscribe(book => console.log('subscriber2: ', book.title))

bookId$.next(1);

console output:

fetch book: Book1
fetch book: Book1 <--- called second time
subscriber1:  Book1
subscriber2:  Book1

What is the best practice to prevent multiple fetches in RxJS?

Upd: I don't use Angular

Upd2: The problem is caused by multiple subscribers

1 Answers

Add shareReplay(1) after your mergeMap(). This will ensure late subscribers will get the last emitted value from the source observable.

Related