【问题标题】:Rxjs: Execute code and emit value on completion of ObservableRxjs:执行代码并在 Observable 完成时发出值
【发布时间】:2019-08-20 13:12:39
【问题描述】:

如何在 Observable 完成时执行一些代码并发出最终值?

RxJS 提供了一个endWith 运算符,它接受一个值以在完成时发出。但是,我想传入一个 valueProvider 函数,该函数应该只在我的 src$ Observable 完成返回应该发出的最终值时执行。

const mapped$ = src$.pipe(
 //only on completion
  endWithCallback(() => {
   const endParam= this.getSomething();
   return endValue;
  }),
);

当然,上面的代码不起作用。我怎样才能实现这样的目标?

【问题讨论】:

  • 如果你想在完成时执行一些代码,在.subscribe完成回调中的调用,这是subscribe方法的第三个参数。你能再解释一下你的问题吗?
  • Rxjs 已经提供了一个 endWith 操作符,它在完成时接受值来发出。我想提供 valueProvider 函数,它将在 src$ 完成时执行并创建一个要发出的值。

标签: rxjs


【解决方案1】:

使用 concatdefer 将 Observable 附加到您的源代码,其内部代码在源代码完成后执行。

concat(src$, defer(() => of(getLast())))

您也可以创建一个执行此操作的运算符。

src$.pipe(withLast(getLast))

// 1. emits the same type as source
export function withLast<T>(getLast: () => T): MonoTypeOperatorFunction<T> {
  return (source: Observable<T>) => concat(source, defer(() => of(getLast())));
}

// 2. emits a different type than source
export function withLastAs<T, R>(getLast: () => R): OperatorFunction<T, R> {
  return (source: Observable<T>) => source.lift.call(
    concat(source, defer(() => of(getLast())))
  );
}

getLast 包含您想要在源代码完成时执行的代码,并返回最后发出的值。

function getLast(): any {
  console.log('on last');
  const endParam = this.getSomething();
  return endValue;
}

【讨论】:

  • 不错。你是救世主:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 2021-03-25
  • 2019-02-05
  • 1970-01-01
  • 2017-06-14
  • 2020-03-26
相关资源
最近更新 更多