我是 RxJS 新手,所以我的术语可能不够简洁,抱歉。我使用 map() 创建了派生的 Observable,并希望它继续通过自身传递其源值以及在此之上的其他事件。例如:
//receiving values from server:
const $source = new Rx.Subject;
//map from network representation to client one:
const $client = $source.map( server => server.x + server.y );
//display on screen:
$client.subscribe( client => console.log( "client:", client ) )
//have input to update client-side representation:
const $button = new Rx.Subject;
$button.subscribe( $client );
$button.next( { x : 1, y : 2 } );
遗憾的是,它打印“3”而不是 Object,就好像 $button 将事件直接发送到 $source 而不是 $client 一样。为什么 $button.next(...) 发送到 $source 而不是发送到 $client?我期望一个运算符(在本例中为map())生成新流。如何实现本地循环,使其仍然依赖于原始流,但不修改原始流?提前致谢。
最佳答案
您所看到的结果是预期的,而您想要实现的结果是不可能的。
I expected an operator (map() in this case) to spawn new stream.
这是正确的,但是新生成的流是 source$
的扩展,因此:
$client = $source + map
// this means any data injected into client$
// will walk through an instance of source$ and then through the map-function
我知道,这仅解释了行为,并没有提供“解决方案” - 但是,为了正确提供解决您的问题的良好答案,您应该写一些有关您正在尝试的内容实现 - 除非您只想了解为什么会这样。
另外:它当前的结构方式看起来确实过于复杂,我相信如果您提供有关用例的一些信息,这可以简化。
关于javascript - next() 到中间 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45394118/