onEffectCleanup function
Registers a cleanup function to be executed when the current effect is disposed or re-run.
Parameters:
fn: The cleanup function to registerowner: Optional effect owner. If not provided, automatically detects the current active effect from the reactive context or the active watcher.
This function can only be called within an effect or watcher context. The cleanup function will be executed before the effect re-runs or when the effect is disposed.
Example:
Effect(() {
final timer = Timer.periodic(Duration(seconds: 1), (_) {});
onEffectCleanup(() => timer.cancel());
});
Implementation
@pragma("vm:prefer-inline")
@pragma("wasm:prefer-inline")
@pragma("dart2js:prefer-inline")
void onEffectCleanup(Disposer fn, {EffectCleanupMixin? owner}) {
final effectiveOwner = owner ?? Watcher.activeWatcher ?? getActiveSub();
if (effectiveOwner == null || effectiveOwner is! EffectCleanupMixin) {
throw StateError(
'onEffectCleanup can only be used within an effect or watcher');
}
effectiveOwner.onCleanUp(fn);
}