diff --git a/src/reactor.js b/src/reactor.js index b31cb21..6483be0 100644 --- a/src/reactor.js +++ b/src/reactor.js @@ -208,26 +208,41 @@ class Reactor { }) }) - observerIdsToNotify.forEach((observerId) => { - const entry = this.observerState.getIn(['observersMap', observerId]) - if (!entry) { - // don't notify here in the case a handler called unobserve on another observer - return + //generates a map with getter as key and an arrays of observer id as value. + const getterObserverMap = observerIdsToNotify.reduce((map, observerId) => { + const entry = this.observerState.getIn(['observersMap', observerId]); + const getter = entry.get('getter'); + const handler = entry.get('handler'); + + let handlerList = map.get(getter); + + if (!handlerList) { + handlerList = Immutable.List(); } - const getter = entry.get('getter') - const handler = entry.get('handler') + handlerList = handlerList.push(handler); + + return map.set(getter, handlerList); + + }, Immutable.Map()); + + // for each getter, evaluate the getter once, then notify all the observers relies on it + getterObserverMap.forEach((handlerList, getter) => { const prevEvaluateResult = fns.evaluate(this.prevReactorState, getter) const currEvaluateResult = fns.evaluate(this.reactorState, getter) + this.prevReactorState = prevEvaluateResult.reactorState + this.reactorState = currEvaluateResult.reactorState + const prevValue = prevEvaluateResult.result const currValue = currEvaluateResult.result if (!Immutable.is(prevValue, currValue)) { - handler.call(null, currValue) + handlerList.forEach(handler => handler.call(null, currValue)); } - }) + + }); const nextReactorState = fns.resetDirtyStores(this.reactorState)