2017-07-29 45 views
2

我是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?我希望在這種情況下運營商(地圖())產生新的流。我怎樣才能實現本地循環仍然依賴於原始流,但不修改原始流?提前致謝。

回答

2

您看到的結果是預期的,而您嘗試實現的結果是不可能的。

我希望一個操作符(在這種情況下是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 

我知道,這只是說明了其行爲,並沒有提供一個「解決方案」 - 然而,要正確地提供一個很好的答案,你應該寫一些關於你想要實現的東西 - 除非你想要明白爲什麼它是這樣的。

另外:它目前的結構看起來過於複雜,如果你提供了有關用例的信息,我相信這可以被簡化。

+0

謝謝你的回答。我只想讓用戶從服務器開始更改值,但是隨時服務器發送任何新值 - 重置用戶看到的內容並繼續從已有的新內容更改。 – Slav

+1

嗯,但這就是你的流目前做的 - 也許你應該看看你的'map'方法,你確定要添加'x'和'y'嗎?也許這是你的問題?請用以下流式圖更新您的問題:什麼數據源會在什麼時候發送哪些數據,以及您希望在數據流的末尾顯示哪些數據。 – olsn

+1

你對** map()**是**擴展**(不管它是什麼)的原始觀察讓我想出解決方案。發佈它作爲答案,謝謝。 – Slav

0

加上中間主體($ 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」 的對象。