River_pod: Is object instantiation with Reader reference preferred over constructor injection?

Created on 16 Aug 2020  路  7Comments  路  Source: rrousselGit/river_pod

Using the read method inside of a provider body is discouraged according to the docs, but the reason for this is unclear to me.

Is there a discernible difference in behavior between the following snippets?

final myServiceProvider = Provider((ref.read) => MyService(ref.read));


//initialization within constructor
MyService(Reader read)
: api=read(apiProvider);
final myServiceProvider = Provider(
    (ref) => MyService(api: ref.read(apiProvider)));

I don't have as much of an issue with passing the reader given that riverpod is compile safe, but constructor injection does have the advantage of making dependencies more explicit. Is this indeed an anti-pattern and if so why?

documentation

All 7 comments

There aren't many reasons.
I just found the code more readable when reading providers, but that's about it.

Thanks for getting back with me. The docs do seem to suggest that this causes unwanted rebuilds.

It may cause less confusion to highlight passing a reference as the idiomatic way to go about instantiation rather than labeling all calls to read inside a provider as a bad practice.

The docs do seem to suggest that this causes unwanted rebuilds.

What are you referring to? Because it doesn't

DON'T call [read] inside the body of a provider

If you want to avoid unwanted rebuilds of your object, see My provider updates too often, what can I do?

That is at least how I interpret the above, sorry if I am missing something.

Ah, this is referring to "if you used read instead of watch to filter rebuilds, don't do that and instead see [link]"

Is that a better wording?

OK I understand and yes that is much more clear. Just a nit but I think that concept would be much more clear either in it's own info message box or perhaps above the code block in that section. Happy to make a pr if that'd help

Done :smile:

Was this page helpful?
0 / 5 - 0 ratings