next()to intermediate Observable
问题描述:
我是RxJS的新手,所以我的术语可能不够简洁,对不起。我使用map()创建了派生Observable,并希望它继续通过其自身传递源值以及其他附加事件。例如:next()to intermediate 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”,而不是对象仿佛$按钮直接将事件发送给$源代替$客户。为什么$ button.next(...)发射到$源而不是发射到$ client?我希望在这种情况下运营商(地图())产生新的流。我怎样才能实现本地循环仍然依赖于原始流,但不修改原始流?提前致谢。
答
您看到的结果是预期的,而您尝试实现的结果是不可能的。
我希望一个操作符(在这种情况下是map())产生新的流。
这是正确的,然而新派生流是扩展source$
,所以:
$client = $source + map
// this means any data injected into client$
// will walk through an instance of source$ and then through the map-function
我知道,这只是说明了其行为,并没有提供一个“解决方案” - 然而,要正确地提供一个很好的答案,你应该写一些关于你想要实现的东西 - 除非你想要明白为什么它是这样的。
另外:它目前的结构看起来过于复杂,如果你提供了有关用例的信息,我相信这可以被简化。
答
加上中间主体($ anotherSource),并与原$源的沿合并解决了这个问题:
//eternal values receive from server:
const $source = new Rx.Subject;
$source.subscribe(() => console.log("Should not"));
const $anotherSource = new Rx.Subject;
//map from network representation:
const $client = $source.map(server => server.x + server.y).merge($anotherSource);
//display on screen:
$client.subscribe(client => console.log("client:", client))
//have input to update client-side representation interleaving with server one:
const $button = new Rx.Subject;
$button.subscribe($anotherSource);
$button.next({ x : 1, y : 2 });
$客户现在收到的,而不是如预期的 “3” 的对象。
谢谢你的回答。我只想让用户从服务器开始更改值,但是随时服务器发送任何新值 - 重置用户看到的内容并继续从已有的新内容更改。 – Slav
嗯,但这就是你的流目前做的 - 也许你应该看看你的'map'方法,你确定要添加'x'和'y'吗?也许这是你的问题?请用以下流式图更新您的问题:什么数据源会在什么时候发送哪些数据,以及您希望在数据流的末尾显示哪些数据。 – olsn
你对** map()**是**扩展**(不管它是什么)的原始观察让我想出解决方案。发布它作为答案,谢谢。 – Slav