riverpod icon indicating copy to clipboard operation
riverpod copied to clipboard

Future provider memory leak

Open Colman opened this issue 2 months ago • 12 comments

Describe the bug Listeners are added when they shouldn't be when using future providers. This leads to a memory leak since the listeners are never removed.

Dependencies

flutter_riverpod: 2.5.1
riverpod_annotation: 2.3.5
riverpod_generator: 2.4.0
riverpod_lint: 2.3.10

Code

@riverpod
Future<int> a(ARef ref) async {
  print('buildA');
  ref.onAddListener(() {
    print('addA');
  });
  ref.onRemoveListener(() {
    print('removeA');
  });
  ref.onCancel(() {
    print('cancelA');
  });
  await Future.delayed(const Duration(seconds: 5));
  await ref.watch(bProvider.future);
  return 5;
}

@riverpod
Future<int> b(BRef ref) async {
  print('buildB');
  ref.onAddListener(() {
    print('addB');
  });
  ref.onRemoveListener(() {
    print('removeB');
  });
  ref.onCancel(() {
    print('cancelB');
  });
  return 6;
}

class SomeScreen extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.watch(aProvider);
    return Container();
  }
}

If you display SomeScreen, then click back within 5 seconds (the delay in aProvider), the following is printed:

buildA
addA
removeA
cancelA
buildB
addB

A listener for bProvider is added but never removed even though nothing is listening to aProvider anymore. Shouldn't aProvider check its own aliveness before adding a listener to bProvider on the line ref.watch(bProvider.future)?

Expected behavior The listener on bProvider should never be added

Colman avatar May 02 '24 05:05 Colman