Skip to content

To make computed property even more efficient

Tyler Long edited this page Oct 11, 2018 · 1 revision

To make computed property even more efficient

We know that computed property caches it result and won't re-compute until necessary.

But if relevant data changes frequently, cache doesn't help at all.

Let's assume that person.fullName() is an expensive computation. And we definitely don't want to execute it again and again in a short peroid of time.

Intead, we only need the last fullName value when firstName and lastName stop changing for a while.

import { debounceTime, map } from 'rxjs/operators'

let count = 0
let fullName
const Person = new SubX({
    firstName: 'San',
    lastName: 'Zhang',
    get fullName () {
        count += 1
        console.log('expensive computation')
        return `${this.firstName} ${this.lastName}`
    }
})
const person = new Person()

person.$.pipe(
    debounceTime(100),
    map(event => person.fullName)
).subscribe(val => {
    fullName = val
})

person.firstName = 'Si'
person.lastName = 'Li'

person.lastName = 'Wang'
person.firstName = 'Wu'

await delay(150)

expect(count).toBe(1) // no more than 1 time of expensive computation
expect(fullName).toBe('Wu Wang')

We use debounceTime(100) so that the expensive operation will not execute until firstName & lastName have stopped changing for 100 milliseconds.

Console output

expensive computation

You can see that expensive computation was only printed once although we changed firstName & lastName four times in total.