Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I emit a single value when observable completes?

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?

like image 291
Marinos An Avatar asked Jan 27 '21 17:01

Marinos An


Video Answer


1 Answers

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);
like image 57
frido Avatar answered Oct 20 '22 06:10

frido