0

In our project, we use the following pattern: we do not get the value from the observable, we add the value to the store inside.

  loadReport() {
    return this.http.get(url, { params: httpParams })
      .pipe(
        tap(
          (obj: X) => {
            this.Store.set(obj);
            this.rStore.setError(null);
          },
          e => {
            this.Store.setError(e);
          }));
  }

When I want to update the store I have to call loadReport().subscibe(). But If you use this several times, then several Obsrvables will be created and the request will be sent several times. How can this problem be solved? pipe(first()) and the like don't help. I just need to execute the loadReport method without getting observable, observable and so it is in the store.

AlexandrT
  • 115
  • 6
  • `pipe(first())` is indeed the solution. If it does not work, please provide a [mcve]. –  May 24 '22 at 07:54
  • What does it mean to update the values without creating an Observable? If you want to update the value, then in any case you need to make a request, and you can only make it by subscribing, this is how the http client works. And what is the actual problem? You don't want the request to be made (but that's weird, if you want to update the value it's necessary). Or is the problem that there are several requests and you want to process only one request at a time? Or do you want to update the store yourself? – bitvalser May 24 '22 at 08:02

2 Answers2

0

if you want to prevent multiple requests on the same httpObservable, you can use the shareReplay operator.

Here is a good tutorial on the topic

Ivan Tarskich
  • 1,332
  • 1
  • 12
  • 19
0

You may want to check take(count).

From rxjs.dev: "take returns an Observable that emits only the first count values emitted by the source Observable. [...] After that, it completes, regardless if the source completes."

Example:

import { interval, take } from 'rxjs';
 
const intervalCount = interval(1000);
const takeFive = intervalCount.pipe(take(1));
takeFive.subscribe(x => console.log(x));
 
// Logs:
// 0
Lorenzo
  • 64
  • 8