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 "!"
Use BehaviorSubject or ReplaySubject instead of Subject or plain Observable, then new subscribers will get the last emitted event as first value.
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