flyingpluto7
flyingpluto7

Reputation: 1099

How to subscribe to an observable once?

My function access() needs to subscribe once, each and every call.

In the snippet below, $valueChanges emits data to each change made. Calling access() without const $ = ... and $.unsubscribe(), $valueChanges observable emits unnecessary streams of values.

Is there an rxjs operator/function that emits once in subscription inside a function? Even if the function is called multiple times the subscription emits once?

access() {
  const $ = $valueChanges.pipe(
    map((res) => 
      ...
    ),
  ).subscribe((res) => {

    ...

    $.unsubscribe();
  });
}

Upvotes: 0

Views: 3260

Answers (2)

satanTime
satanTime

Reputation: 13584

Try shareReply(1). Then the original stream will be called only once and its emit will be shared with all subscribers. If the stream emits 2nd time - the update will go to all subscribers too.

access() {
  const $ = $valueChanges.pipe(
    map((res) => 
      ...
    ),
    // take(1), // in case if you need just 1 emit from it.
    shareReply(1), // in case if you don't want to trigger `$valueChanges` on every subscription.
  ).subscribe((res) => {

    ...

    // $.unsubscribe(); // it's useless in case of `take(1)`.
  });
}

Upvotes: 1

wentjun
wentjun

Reputation: 42586

You can consider using the take() operator, and emit only the first value before completing.

According to the documentation, the take operator

Emit provided number of values before completing.

This is how you can use it:

access() {
  valueChanges
    .pipe(
      map((res) => 
        ...
      ),
      take(1),
    ).subscribe((res) => {

      ...

    });
}

Upvotes: 4

Related Questions