addEffect method
Adds an effect function that gets called whenever the value changes.
Effects are a way to perform side effects when a reactive value changes without modifying the value itself. The effect function receives a Snapshot containing both the old and new values.
This method returns a StreamSubscription that can be used to cancel the effect if needed.
Example:
final counter = Reactive(0);
// Add a logging effect
counter.addEffect((snapshot) {
print('Counter changed from ${snapshot.oldValue} to ${snapshot.newValue}');
});
// Add a persistence effect
counter.addEffect((snapshot) {
saveToLocalStorage('counter', snapshot.newValue);
});
counter.value = 1; // Both effects will be triggered
Note: Effects are implemented using stream subscriptions. To avoid memory leaks, ensure you cancel any subscriptions when they're no longer needed, or dispose the reactive instance.
Implementation
StreamSubscription<Snapshot<T>> addEffect(Function(Snapshot<T>) effect) {
return stream.listen((snapshot) {
effect(snapshot);
});
}