riverpod icon indicating copy to clipboard operation
riverpod copied to clipboard

Am I allowed to `ref.watch` in a `FutureProvider` across async gap?

Open fzyzcjy opened this issue 2 years ago • 5 comments

For example,

final myProvider = FutureProvider<Something>((ref) async {
  final a = ref.watch(aProvider);
  final b = await fetchNetworkData(a);
  final c = ref.watch(cProvider); // <---- NOTE this line
  return ...;
});

If it is supported, maybe the doc can mention it a little bit, because I am familiar with MobX which does not support this. Given popularity of MobX, I guess many people will have the same confusion as me, so doc is helpful.

If it is not supported, then this issue is a feature request :)

fzyzcjy avatar Sep 04 '22 02:09 fzyzcjy

Yes, it is supported, note that the provider will only rebuild when aProvider changes until the await completes successfully, at which point cProvider is watched, after which the provider will rebuild whenever cProvider changes as well.

TimWhiting avatar Sep 04 '22 05:09 TimWhiting

Thank you!

fzyzcjy avatar Sep 04 '22 05:09 fzyzcjy

There are no constraints on when to call ref.watch/ref.read, only good/bad practices.

For example, you can call ref.read inside build. It's considered a bad idea, but you can. Same goes for ref.watch inside a button's onPressed.

rrousselGit avatar Sep 07 '22 09:09 rrousselGit

But could those bad practices cause breakage/exceptions or unnecessary widget rebuilds?

levi956 avatar Sep 09 '22 23:09 levi956

No that should be fine

It'll behave as you would expect: if the watched provider changes, the widget/provider will rebuild.

Le sam. 10 sept. 2022 à 01:38, Nifesi Odumirin @.***> a écrit :

But could those bad practices cause breakage/exceptions or unnecessary widget rebuilds?

— Reply to this email directly, view it on GitHub https://github.com/rrousselGit/riverpod/issues/1603#issuecomment-1242559236, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEZ3I3LDUYY7PFYOKEKX72TV5PC6FANCNFSM6AAAAAAQEEKC74 . You are receiving this because you commented.Message ID: @.***>

rrousselGit avatar Sep 10 '22 06:09 rrousselGit

@rrousselGit

As you mentioned,

if the watched provider changes, the widget/provider will rebuild.

But it doesn't seem to be working as expected. Could you please take a look at this question on StackOverflow?

iLoveDocs avatar Sep 25 '22 13:09 iLoveDocs