rxjs:使用流两次引用已经在上游完成的可观察对象
rxjs: use stream referring twice to an observable that has already completed upstream
我在使用 hot observable 后获取值时遇到问题。
const partialState$ = Rx.Observable.of(1)
.publish().refCount();
const downstreamState$ = partialState$.map(v => ([v+1, v+2]));
const finalState$ = downstreamState$
// last value of partialState$ being requested -
// shouldn't matter if its completed through earlier chaining
.withLatestFrom(partialState$)
finalState$.subscribe(state => { // this does not fire
console.log('state', state);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.5/Rx.js"></script>
这是 fiddle:http://jsfiddle.net/j64te6jp/10/
上面的代码什么都不做 - 似乎由于订阅的同步行为,partialState$
在被推入 .subscribe
之前没有被标记为有值就绪
这永远不会发生,因为当 downStreamState$
从中请求最新值时 partialState$
还不存在任何值。
有人可以解释为什么会发生这种情况,并提供一种从热(已发布)可观察对象中重新使用相同值的好方法。谢谢。
发生这种情况是因为您在发出值后进行了订阅。为什么不使用 .publishReplay()
?
如果你还是想避开publishReplay()
,你可以使用.delay(0)
:
const partialState$ = Rx.Observable.of(1).delay(0)
.publish().refCount();
这是向我建议的解决方案 - 非常感谢 https://github.com/Dorus
const partialState$ = Rx.Observable.of(1)
.do(() => console.log('i will be run once'))
const finalState$ = partialState$.publish(partialState_ => {
const downstreamState$ = partialState_.map(v => ([v+1, v+2]));
return downstreamState$
.withLatestFrom(partialState_)
})
finalState$.subscribe(state => {
console.log('state', state);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.5/Rx.js"></script>
我在使用 hot observable 后获取值时遇到问题。
const partialState$ = Rx.Observable.of(1)
.publish().refCount();
const downstreamState$ = partialState$.map(v => ([v+1, v+2]));
const finalState$ = downstreamState$
// last value of partialState$ being requested -
// shouldn't matter if its completed through earlier chaining
.withLatestFrom(partialState$)
finalState$.subscribe(state => { // this does not fire
console.log('state', state);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.5/Rx.js"></script>
这是 fiddle:http://jsfiddle.net/j64te6jp/10/
上面的代码什么都不做 - 似乎由于订阅的同步行为,partialState$
在被推入 .subscribe
之前没有被标记为有值就绪
这永远不会发生,因为当 downStreamState$
从中请求最新值时 partialState$
还不存在任何值。
有人可以解释为什么会发生这种情况,并提供一种从热(已发布)可观察对象中重新使用相同值的好方法。谢谢。
发生这种情况是因为您在发出值后进行了订阅。为什么不使用 .publishReplay()
?
如果你还是想避开publishReplay()
,你可以使用.delay(0)
:
const partialState$ = Rx.Observable.of(1).delay(0)
.publish().refCount();
这是向我建议的解决方案 - 非常感谢 https://github.com/Dorus
const partialState$ = Rx.Observable.of(1)
.do(() => console.log('i will be run once'))
const finalState$ = partialState$.publish(partialState_ => {
const downstreamState$ = partialState_.map(v => ([v+1, v+2]));
return downstreamState$
.withLatestFrom(partialState_)
})
finalState$.subscribe(state => {
console.log('state', state);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.5/Rx.js"></script>