Home > Software design >  how just execute observable one time
how just execute observable one time

Time:05-24

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related