Skip to content

Commit f6df576

Browse files
authored
Merge pull request mobxjs#1499 from kuitos/fork-master
avoid the unnecessary reassign with the equivalent comparison result
2 parents 09493ee + cff477c commit f6df576

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

‎src/core/computedvalue.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,13 +197,19 @@ export class ComputedValue<T> implements IObservable, IComputedValue<T>, IDeriva
197197
const oldValue = this.value
198198
const wasSuspended =
199199
/* see #1208 */ this.dependenciesState === IDerivationState.NOT_TRACKING
200-
const newValue = (this.value = this.computeValue(true))
201-
return (
200+
const newValue = this.computeValue(true)
201+
202+
const changed =
202203
wasSuspended ||
203204
isCaughtException(oldValue) ||
204205
isCaughtException(newValue) ||
205206
!this.equals(oldValue, newValue)
206-
)
207+
208+
if (changed) {
209+
this.value = newValue
210+
}
211+
212+
return changed
207213
}
208214

209215
computeValue(track: boolean) {

‎test/base/babel-tests.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,29 @@ test("babel: parameterized computed decorator", () => {
102102
expect(changes).toEqual([{ sum: 6 }, { sum: 7 }, { sum: 9 }])
103103
})
104104

105+
test("computed value should be the same around changing which was considered equivalent", () => {
106+
class TestClass {
107+
@observable c = null
108+
defaultCollection = []
109+
@computed.struct
110+
get collection() {
111+
return this.c || this.defaultCollection
112+
}
113+
}
114+
115+
const t1 = new TestClass()
116+
117+
const d = autorun(() => t1.collection)
118+
119+
const oldCollection = t1.collection
120+
t1.c = []
121+
const newCollection = t1.collection
122+
123+
expect(oldCollection).toBe(newCollection)
124+
125+
d()
126+
})
127+
105128
class Order {
106129
@observable price = 3
107130
@observable amount = 2

0 commit comments

Comments
 (0)