Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs: - receive values emitted before subscribe

my emit.next(1) is lost, I want my subscriber to get that value. My subscriber can't subscribe until after the emit has already happened.

This answer suggests publish and connect RxJs: how to get values emitted before we subscribe? however I wasn't sure how to get it working:

console.log('make emit')
let emit = new Subject<number>();
console.log('make obs')
let obs = emit.asObservable()
console.log('emit 1')
emit.next(1)
console.log('subscribe')
obs.subscribe((v)=>console.log(v,'!'))
console.log('emit 2')
emit.next(2)
console.log('set timeout 1000 to emit')
setTimeout(()=>emit.next(3),1000)
console.log('done')

output:

make emit
main.bundle.js:1561 make obs
main.bundle.js:1563 emit 1
main.bundle.js:1565 subscribe
main.bundle.js:1567 emit 2
main.bundle.js:1566 2 "!"
main.bundle.js:1569 set timeout 1000 to emit
main.bundle.js:1571 done
main.bundle.js:1566 3 "!"

it should log 1 "!"

like image 297
robert king Avatar asked Aug 01 '17 11:08

robert king


1 Answers

Use BehaviorSubject or ReplaySubject instead of Subject or plain Observable, then new subscribers will get the last emitted event as first value.

like image 79
Günter Zöchbauer Avatar answered Oct 13 '22 00:10

Günter Zöchbauer