我有一个热门观察,我经常需要手动触发。我使用Subject
来实现这一目标。我想:
您可以在以下脚本中观察我尝试失败。我认为该脚本显示了明确的意图,但并未按预期执行。你能找出我失踪的东西吗?
void async function () {
var subject = new Rx.Subject()
var inner = subject.combineLatest([subject]).share()
// ^^ i have other observables here in addition to the subject
// in my real use case. also, i want the observable hot!
var i = 1
while (i <= 3) {
console.log(`i is ${i}, print ${i} before "i is ${i + 1}"`)
var singleValObs = inner.take(1) // prep to observe the next value
subject.next(i) // trigger the next value
var [val] = await singleValObs.toPromise()
console.log(val)
++i
}
}()
我希望1,2和&amp; 3要记录,但只记录一行!
我是rx的新手,但非常喜欢它背后的想法。感谢先进的提示!
答案 0 :(得分:2)
您的承诺是在主题发出值后创建的,因此它永远不会得到解决。您必须首先创建承诺,然后调用next(i)
然后等待承诺,特别是:
var singleValObs = inner.take(1) // prep to observe the next value
var promise = singleValObs.toPromise();
subject.next(i) // trigger the next value
var [val] = await promise
或者,使用ReplaySubject
也会向后期订阅者发放值。