rodydavis / signals.dart

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

LateInitializationError on computed when using peek() #260

Closed alfalcon90 closed 2 months ago

alfalcon90 commented 2 months ago

I think the latest change to computed (https://github.com/rodydavis/signals.dart/commit/e2fab8906babdeaf80cf4261e02816a210b15540) introduced a new bug in v5.1.0. The test below throws a LateError (LateInitializationError: Field '_value@685309559' has not been initialized.) error on this line: https://github.com/rodydavis/signals.dart/blob/cd1711fa3243a4cad3cc3c3602d4b70cdcdbd80e/packages/signals_core/lib/src/core/computed.dart#L357

This test passed before the change was made.

 test('peek() works as intended', () {
      final foo = Foo();
      final c = foo.value;
      expect(c, 1);
    });

class Foo {
  final s = signal(0);
  late final c = computed(() => s.value + 1);
  int get value => c.peek();
}

My temp workaround

extension ReadonlySignalExt<T> on ReadonlySignal<T> {
  /// Returns the value of the signal without tracking it.
  T get untracked {
    late T v;
    s.untracked(() => v = value);
    return v;
  }
}
rodydavis commented 2 months ago

Yeah it was actually a bug before, this is now the correct implementation.

Computed cannot be peeked if the value is not read. Because it cannot trigger subscriptions.

The latest commits put it in sync with the upstream implementation.