I want to emit one value when the original observable completes let's say like below, using the imaginary operator mapComplete
:
let arr = ['a','b', 'c'];
from(arr)
.pipe(mapComplete(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log)
//further processed: myValue
I tried the following which work but don't seem suitable:
1.
from(arr)
.pipe(toArray())
.pipe(map(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log);
//further processed: myValue
Issue: If the original observable is a huge stream, i don't want to buffer it to an array, just to emit one value.
2.
from(arr)
.pipe(last())
.pipe(map(()=>'myValue'))
.pipe(map((v)=>`further processed: ${v}`))
.subscribe(console.log);
//further processed: myValue
issue: If the stream completes without emitting anything I get an error: [Error [EmptyError]: no elements in sequence]
What would be a correct (in rxjs terms) way to do the above?
You can achieve this with ignoreElements
to not emit anything and endWith
to emit a value on complete.
from(arr).pipe(
ignoreElements(),
endWith('myValue'),
map(v => `further processed: ${v}`)
).subscribe(console.log);
If you want to execute a function in map
you could use count()
beforehand to emit one value on complete (the amount of values emitted).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With