rxjs:使用流引用两次到已经完成上游的observable

时间:2016-12-07 22:38:36

标签: javascript stream rxjs reactive-programming reactivex

我在使用后从热观察中获取值时遇到问题。

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>

这是小提琴:http://jsfiddle.net/j64te6jp/10/

上面的代码什么也没做 - 似乎是由于订阅的同步行为,partialState$在被推入.subscribe之前未被标记为准备就绪 当partialState$downStreamState$请求最新信息时,svn ls -Rv your_svn_host/your_project 还没有值,因此从未发生过这种情况。

有人可以解释为什么会发生这种情况,并提供一种从热门(已发布)可观察量中重复使用相同值的好方法。感谢。

2 个答案:

答案 0 :(得分:0)

这是因为您在发出值后订阅了。为什么不使用import {SomeCompoent} from "bundleTwo";

如果您仍想避免.publishReplay(),可以使用publishReplay()

.delay(0)

答案 1 :(得分:0)

以下是我建议的解决方案 - 非常感谢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>