简体   繁体   中英

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();
  });
}

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) => {

      ...

    });
}

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)`.
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM