rxjs: - receive values emitted before subscribe

2019-06-04 17:10发布

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 "!"

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-04 17:30

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

查看更多
登录 后发表回答