当 observable 完成时,我应该如何发出单个值?

Mar*_* An 4 observable rxjs rxjs6

我想在原始 observable 完成时发出一个值,让我们像下面这样说,使用虚运算符mapComplete

let arr = ['a','b', 'c'];

from(arr)
.pipe(mapComplete(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log)
//further processed: myValue
Run Code Online (Sandbox Code Playgroud)

我尝试了以下工作但似乎不合适的方法:

1.

from(arr)
.pipe(toArray())
.pipe(map(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log);
//further processed: myValue
Run Code Online (Sandbox Code Playgroud)

问题:如果原始 observable 是一个巨大的流,我不想将它缓冲到一个数组中,只是为了发出一个值。

2.

from(arr)
.pipe(last())
.pipe(map(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log);
//further processed: myValue
Run Code Online (Sandbox Code Playgroud)

问题:如果流完成而不发出任何内容,我会收到错误消息:[Error [EmptyError]: no elements in sequence]

执行上述操作的正确方法(在 rxjs 中)是什么?

fri*_*doo 6

您可以ignoreElements通过不发出任何内容并endWith在完成时发出值来实现这一点。

from(arr).pipe(
  ignoreElements(),
  endWith('myValue'),
  map(v => `further processed: ${v}`)
).subscribe(console.log);
Run Code Online (Sandbox Code Playgroud)

如果您想在其中执行一个函数,map您可以count()预先使用在完成时发出一个值(发出的值的数量)。

from(arr).pipe(
  count(), // could also use "reduce(() => null, 0)" or "last(null, 0)" or "takeLast(1), defaultIfEmpty(0)" 
  map(() => getMyValue()),
  map(v => `further processed: ${v}`)
).subscribe(console.log);
Run Code Online (Sandbox Code Playgroud)