如何订阅一次可观察者?

时间:2020-05-29 02:02:54

标签: javascript angular reactjs typescript rxjs

我的函数access()需要订阅一次,每次调用。

在下面的代码段中,$valueChanges会针对所做的每个更改发出数据。 access()调用const $ = ...而没有$.unsubscribe()$valueChanges的情况下,则会发出不必要的值流。

函数内部是否存在一个在订阅中发出一次的rxjs运算符/函数?即使多次调用该函数,订阅也会发出一次?

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

    ...

    $.unsubscribe();
  });
}

2 个答案:

答案 0 :(得分:4)

您可以考虑使用take()运算符,并在完成之前仅发出第一个值。

根据documentationtake运算符

Emit provided number of values before completing.

这是您可以使用的方式:

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

      ...

    });
}

答案 1 :(得分:1)

尝试shareReply(1)。然后,原始流将仅被调用一次,并且其发射将与所有订户共享。如果数据流发出第二次信号-更新也将发送给所有订阅者。

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