创建惰性可观察对象 {🚀}
用法
onBecomeObserved(observable, property?, listener: () => void): (() => void)
onBecomeUnobserved(observable, property?, listener: () => void): (() => void)
函数 onBecomeObserved
和 onBecomeUnobserved
可以用来为现有的可观察对象附加惰性行为或副作用。它们钩入 MobX 的可观察性系统,并在可观察对象 *开始* 和 *停止* 被观察时收到通知。它们都返回一个 *取消者* 函数,该函数会分离 *监听器*。
在下面的例子中,我们使用它们仅在观察到的值实际使用时执行网络获取。
export class City {
location
temperature
interval
constructor(location) {
makeAutoObservable(this, {
resume: false,
suspend: false
})
this.location = location
// Only start data fetching if temperature is actually used!
onBecomeObserved(this, "temperature", this.resume)
onBecomeUnobserved(this, "temperature", this.suspend)
}
resume = () => {
log(`Resuming ${this.location}`)
this.interval = setInterval(() => this.fetchTemperature(), 5000)
}
suspend = () => {
log(`Suspending ${this.location}`)
this.temperature = undefined
clearInterval(this.interval)
}
fetchTemperature = flow(function* () {
// Data fetching logic...
})
}