遅延観測を構築 {🚀}
用法
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...
})
}