rodydavis / signals.dart

Reactive programming made simple for Dart and Flutter
http://dartsignals.dev
Apache License 2.0
438 stars 50 forks source link

Recommended way of using reset() #210

Closed alfalcon90 closed 6 months ago

alfalcon90 commented 7 months ago

It seems like this workaround is no longer possible: https://github.com/rodydavis/signals.dart/issues/181#issuecomment-1955493463

My current solution is to use extensions but I'm afraid this might break in unpredictable and hard-to-debug ways down the road.

extension SignalExt<T> on Signal<T> {
  /// Get the last value before the last update or the initial value. This does not subscribe in an effect (this is the equivalent to peek())
  T? get previousValue => (this as TrackedReadonlySignal<T>).previousValue;

  /// Get the value the signal was created with and does not subscribe in an effect (this is the equivalent to peek())
  T get initialValue => (this as TrackedReadonlySignal<T>).initialValue;

  /// Resets the value of a [Signal] to its initial value.
  void reset() => set(initialValue);
}
rodydavis commented 6 months ago

Can you not do set(..., force: true) ?

rodydavis commented 6 months ago

I also am mostly likely going to make reset public or similar name.

There is also the .overrideWith too

alfalcon90 commented 6 months ago

I could use set() but if I ever change the initialValue I have to make sure every instance of set(initialValue) is updated. I also have to look up the initialValue every time I want to reset it just to make sure. It just creates more potential for messing something up.

rodydavis commented 6 months ago

I would recommend using overrideWith now for computed and signal.

This will update the value/initial value/previous value and also reset the version to 0.