Skip to content

isAutoDispose #4080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 24, 2025
Merged

isAutoDispose #4080

merged 2 commits into from
Apr 24, 2025

Conversation

rrousselGit
Copy link
Owner

@rrousselGit rrousselGit commented Apr 24, 2025

Summary by CodeRabbit

  • New Features
    • Added an optional parameter to provider builders allowing users to specify auto-dispose behavior directly when creating providers.
  • Documentation
    • Updated changelog to reflect the new auto-dispose usage pattern with a boolean parameter.
  • Tests
    • Introduced comprehensive tests to verify the default and explicit auto-dispose behavior across provider types.
  • Chores
    • Improved code generation and annotations for builder classes to support the new auto-dispose parameter and streamline APIs.

Copy link

coderabbitai bot commented Apr 24, 2025

Walkthrough

This update introduces an optional isAutoDispose boolean parameter (defaulting to false) to the call methods of various provider family builder classes in Riverpod, including functional, notifier, and legacy providers. The parameter allows explicit control over whether a provider should be auto-disposed. The change is reflected across implementation files, code generation scripts, and is documented in the changelog. Comprehensive tests are added to verify the correct behavior of the isAutoDispose flag across all relevant provider constructors. Additionally, builder class annotations and signatures are updated to standardize this new parameter.

Changes

File(s) Change Summary
packages/riverpod/lib/src/builder.dart, packages/flutter_riverpod/lib/src/builders.dart Added optional isAutoDispose parameter (default false) to the call methods of all provider family builder classes; parameter is forwarded to provider constructors. Minor indentation fix in one builder class.
tools/generate_providers/bin/generate_providers.dart Updated code generation to add isAutoDispose parameter to builder classes and their call methods (except for autoDispose variants), removed obsolete parameters (persist, shouldPersist), added a new @publicInMisc annotation, and refactored helper functions to generate the correct parameter and argument strings for isAutoDispose.
packages/riverpod/CHANGELOG.md Documented the new usage pattern for specifying auto-dispose via the isAutoDispose parameter in provider constructors, replacing the previous Provider.autoDispose() and Provider.autoDispose.family() syntax.
packages/riverpod/test/feature/auto_dispose_test.dart Added a new test file to systematically verify default and explicit isAutoDispose behavior for all provider types, using a matrix of provider constructors wrapped by a generic builder class and testing both default and true values of isAutoDispose.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ProviderFamilyBuilder
    participant ProviderFamily

    User->>ProviderFamilyBuilder: call(create, isAutoDispose: true/false)
    ProviderFamilyBuilder->>ProviderFamily: new(create, isAutoDispose: true/false)
    ProviderFamily-->>ProviderFamilyBuilder: ProviderFamily instance
    ProviderFamilyBuilder-->>User: ProviderFamily instance
Loading

Possibly related PRs

  • rrousselGit/riverpod#4064: Adds explicit isAutoDispose overrides and unifies auto-dispose handling in generated provider family classes, directly related to the changes in handling isAutoDispose here.

Poem

In the garden of code where providers bloom,
A new flag appears—autoDispose makes room!
Builders now whisper, “Dispose me, or not?”
With tests as our rain and changelogs our plot.
The rabbits all cheer, for control is now clear—
Riverpod’s meadows are tidier this year!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between baeb8ed and a5470ea.

📒 Files selected for processing (2)
  • packages/flutter_riverpod/lib/src/builders.dart (1 hunks)
  • packages/riverpod/lib/src/builder.dart (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/flutter_riverpod/lib/src/builders.dart
  • packages/riverpod/lib/src/builder.dart
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: build (master, packages/riverpod)
  • GitHub Check: build (master, packages/riverpod/example)
  • GitHub Check: build (master, packages/flutter_riverpod)
  • GitHub Check: build (master, examples/marvel)
  • GitHub Check: riverpod_lint (stable, packages/riverpod_lint_flutter_test)
  • GitHub Check: riverpod_lint (master, packages/riverpod_analyzer_utils_tests)
  • GitHub Check: riverpod_lint (stable, packages/riverpod_analyzer_utils_tests)
  • GitHub Check: check_generation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/riverpod/CHANGELOG.md (1)

3-3: Clarify the new syntax with an explicit “since” version marker

The bullet nicely explains the new isAutoDispose parameter, but it is easy to miss in a sea of other changes. Consider explicitly prefixing the sentence with the version tag (e.g. “Since 3.0.0-dev.x: …”) so that readers can immediately see when the change became available.

tools/generate_providers/bin/generate_providers.dart (2)

260-266: Parameter ordering: keep the often-used isAutoDispose close to name

In the generated call methods, isAutoDispose is placed after rarely-used parameters (dependencies, retry). To improve discoverability, consider moving it right after name.

-    String? name,
-    Iterable<ProviderOrFamily>? dependencies,
-    Retry? retry,
-    bool isAutoDispose = false,
+    String? name,
+    bool isAutoDispose = false,
+    Iterable<ProviderOrFamily>? dependencies,
+    Retry? retry,

This mirrors the mental model: most users toggle auto-dispose and give the provider a name before tweaking advanced knobs.

Also applies to: 298-304, 417-418


369-380: Trailing comma handled by DartFormatter, but an empty string could still trip string-based tooling

_isAutoDisposeArg returns an empty string for the auto-dispose variant.
If another tool (e.g. a doc generator) parses parameters via regex rather than the formatted output, the missing comma could produce false positives. Returning null and letting the caller decide whether to add a comma avoids that subtle edge case:

-String _isAutoDisposeArg(_DisposeType disposeType) {
-  if (disposeType == _DisposeType.autoDispose) return '';
-  return 'bool isAutoDispose = false,';
-}
+String? _isAutoDisposeArg(_DisposeType disposeType) {
+  if (disposeType == _DisposeType.autoDispose) return null;
+  return 'bool isAutoDispose = false,';
+}

Call-sites would wrap the interpolation in a null-aware operator.
Only a minor robustness tweak.

packages/flutter_riverpod/lib/src/builders.dart (1)

232-244: Add a short doc comment for the new isAutoDispose parameter

The method signature now exposes isAutoDispose, but users scanning the huge existing docstring won’t see what the flag does or why they might need it.

-    bool isAutoDispose = false,
+    /// Whether the created provider should be automatically disposed when it
+    /// no longer has listeners. Defaults to `false`.
+    bool isAutoDispose = false,

A one-liner keeps the public API self-documenting, especially when IDEs show parameter hints.

packages/riverpod/lib/src/builder.dart (1)

1-883: Overall code changes look good, consider adding documentation for the new parameter.

The implementation of the isAutoDispose parameter across all provider family builders is consistent and thorough. All auto-dispose variants correctly set isAutoDispose: true internally, while the regular variants default to false.

While the codebase has extensive documentation for other features, consider adding specific documentation for the new isAutoDispose parameter in the method signatures to help users understand its purpose.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 36a61e3 and baeb8ed.

📒 Files selected for processing (5)
  • packages/flutter_riverpod/lib/src/builders.dart (2 hunks)
  • packages/riverpod/CHANGELOG.md (1 hunks)
  • packages/riverpod/lib/src/builder.dart (16 hunks)
  • packages/riverpod/test/feature/auto_dispose_test.dart (1 hunks)
  • tools/generate_providers/bin/generate_providers.dart (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: riverpod_lint (master, packages/riverpod_lint_flutter_test)
  • GitHub Check: riverpod_lint (stable, packages/riverpod_lint_flutter_test)
  • GitHub Check: riverpod_lint (master, packages/riverpod_lint)
  • GitHub Check: riverpod_lint (stable, packages/riverpod_analyzer_utils_tests)
  • GitHub Check: riverpod_lint (master, packages/riverpod_analyzer_utils)
  • GitHub Check: build (master, packages/hooks_riverpod/example)
  • GitHub Check: build (master, packages/flutter_riverpod/example)
  • GitHub Check: riverpod_lint (master, packages/riverpod_analyzer_utils_tests)
  • GitHub Check: build (master, examples/random_number)
  • GitHub Check: build (master, packages/riverpod)
  • GitHub Check: build (master, examples/stackoverflow)
  • GitHub Check: build (master, examples/pub)
  • GitHub Check: build (stable, packages/riverpod/example)
  • GitHub Check: build (stable, examples/random_number)
  • GitHub Check: check_generation
🔇 Additional comments (13)
tools/generate_providers/bin/generate_providers.dart (1)

248-254:

❓ Verification inconclusive

@publicInMisc may require an explicit import

You added @publicInMisc on every generated builder, but this file does not import the library that defines that annotation.
If internals.dart does not export it, generated code will not compile.

-import 'internals.dart';
+import 'internals.dart';
+import 'package:riverpod/src/public_in_misc.dart'; // or wherever the annotation lives

Please double-check the annotation’s location (or re-export it from internals.dart) so the generated source stays self-contained.

Also applies to: 286-294


🏁 Script executed:

#!/bin/bash
# Locate internals.dart file(s) in the repo
internals_paths=$(fd -HI internals.dart)
echo "Found internals.dart at:"
echo "$internals_paths"

# Show export statements in each internals.dart
echo -e "\nExport statements in internals.dart:"
grep -R "export" -n $internals_paths || true

# Search the entire repo for the definition of PublicInMisc or its usage
echo -e "\nDefinition or declaration of PublicInMisc:"
rg "class PublicInMisc" -n .

echo -e "\nOccurrences of publicInMisc in code:"
rg "publicInMisc" -n .

Length of output: 6541


🏁 Script executed:

#!/bin/bash
# Locate generate_providers.dart file
file=$(fd -HI generate_providers.dart | grep "tools/generate_providers/bin")
echo "Found generate_providers.dart at: $file"

# Show the imports and context around internals.dart
echo -e "\nImports in generate_providers.dart:"
sed -n '1,100p' "$file" | grep -n "^import"

# Show the relative path for internals.dart import
echo -e "\nLines importing internals.dart:"
grep -n "internals.dart" -n "$file"

Length of output: 803


🏁 Script executed:

# After inspecting the imports, show if common/internal_lints.dart is referenced
grep -n "internal_lints.dart" -n "$file" || echo "No direct import of internal_lints.dart"

Length of output: 158


🏁 Script executed:

# Check if the local internals.dart near generate_providers.dart exists and what's inside
dir=$(dirname "$file")
if [ -f "$dir/internals.dart" ]; then
  echo -e "\nContents of $dir/internals.dart:"
  sed -n '1,50p' "$dir/internals.dart"
else
  echo "No local internals.dart next to generate_providers.dart"
fi

Length of output: 172


Add explicit import for publicInMisc in generated providers

The generation script emits @publicInMisc but only writes

import 'internals.dart';

If your local internals.dart stub doesn’t re-export common/internal_lints.dart, the generated files won’t compile.

  • In tools/generate_providers/bin/generate_providers.dart (around lines 172 & 194), update the import block to:
 buffer.writeln("import 'internals.dart';");
+buffer.writeln("import 'package:riverpod/src/common/internal_lints.dart';"); // for @publicInMisc

This ensures @publicInMisc is in scope.
Alternatively, re-export publicInMisc from your local internals.dart so the generated code stays self-contained.

packages/riverpod/test/feature/auto_dispose_test.dart (4)

7-24: Well-designed Builder class for flexible provider testing.

The Builder class provides an elegant way to wrap various provider constructors for testing with the isAutoDispose parameter. It handles different parameter cases well and throws appropriate errors for invalid input.


26-38: Good use of extensions for handling different function signatures.

The extensions on the Builder class effectively handle different provider constructor signatures, providing a consistent interface through the unimplemented getter.


40-60: Comprehensive test matrix with good organization.

The matrix effectively organizes all provider types into functional, notifier, and legacy categories, ensuring thorough test coverage across the Riverpod ecosystem.


62-82: Thorough test cases for both default and explicit isAutoDispose values.

These tests effectively verify that:

  1. The default isAutoDispose value is false for all providers
  2. Setting isAutoDispose: true is correctly reflected on the provider instances

This ensures consistency across all provider types with the new API.

packages/riverpod/lib/src/builder.dart (8)

231-245: Consistent implementation of isAutoDispose parameter for StateProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of StateProviderFamily.


353-369: Consistent implementation of isAutoDispose parameter for StateNotifierProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of StateNotifierProviderFamily.


426-446: Consistent implementation of isAutoDispose parameter for ProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of ProviderFamily.


501-521: Consistent implementation of isAutoDispose parameter for FutureProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of FutureProviderFamily.


576-596: Consistent implementation of isAutoDispose parameter for StreamProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of StreamProviderFamily.


678-699: Consistent implementation of isAutoDispose parameter for NotifierProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of NotifierProviderFamily.


756-777: Consistent implementation of isAutoDispose parameter for StreamNotifierProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of StreamNotifierProviderFamily.


834-855: Consistent implementation of isAutoDispose parameter for AsyncNotifierProviderFamilyBuilder.

The isAutoDispose parameter has been correctly added with a default value of false and is properly forwarded to the constructor of AsyncNotifierProviderFamily.

@rrousselGit rrousselGit merged commit 8e8af03 into master Apr 24, 2025
45 checks passed
@rrousselGit rrousselGit deleted the test-autodispose branch April 24, 2025 15:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant