2016-11-19 111 views
0

我有很多Reducer查詢,我需要鏈接到行爲主題。目前我正在爲此做好每一件!@ngrx - 將商店查詢鏈接到BehaviorSubject

有沒有更簡潔的方式來表達這一點?

this._higherCurveObservable = this.store.let(getCurveSummaryForInstrumentTimeframe(this._instrument, this._timeframe.Code)); 
this._higherCurveSubject = <BehaviorSubject<CurveSummary>>new BehaviorSubject(null).distinctUntilChanged(); 
this._higherCurveSubscription = this._higherCurveObservable.subscribe(x => this._higherCurveSubject.next(x)); 
this._higherCurveSubject.subscribe(x => this.higherCurveChange(x)); 

回答

1

應該沒有必要創建單獨的BehaviourSubjects,你可能只是你的基礎上需要儲存流Observables

(唯一一次當你需要這樣的東西 - 而我並不假定你這樣做 - 當你試圖濫用BehaviourSubject以便能夠從商店獲取數據時,情況就是如此從側面,在這種情況下,你應該重新考慮架構調度數據,因爲這將違背概念的ngrx具有單中心店)

所以不存在要與較少的開銷寫這篇多種方式。


實施例1:一個永久的訂閱,從未取消訂閱(例如,在服務)

this.store 
    .let(getCurveSummaryForInstrumentTimeframe(this._instrument, this._timeframe.Code)) 
    .distinctUntilChanged() 
    .do(x => this.higherCurveChange(x)) 
    .subscribe(); 

實施例2:臨時訂閱,應該在一個退訂特定的時間點(例如,在組件中,當組件被銷燬時它應該取消訂閱)

const higherCurve$: Observable<CurveSummary> = this.store 
    .let(getCurveSummaryForInstrumentTimeframe(this._instrument, this._timeframe.Code)) 
    .distinctUntilChanged(); 
this._higherCurveSubscription = higherCurve$.subscribe(x => this.higherCurveChange(x)); 

// ... some time later 
this._higherCurveSubscription.unsubscribe(); 
+0

非常有幫助!謝謝!你說得對,我濫用行爲主題。我現在有一個單一的中央數據存儲區,它的工作非常漂亮! – reach4thelasers