Home > database >  Riverpod Stream Provider, its better to watch or read a stream?
Riverpod Stream Provider, its better to watch or read a stream?

Time:09-03

In the documentation:

Whenever possible, prefer using ref.watch over ref.read or ref.listen to implement a feature.

By relying on ref.watch, your application becomes both reactive and declarative, which makes it more maintainable.

Lets say I have a StreamProvider listen to authStateChanges() in firebase:

class AuthRepo {
......
Stream<User> get user {
    return _firebaseAuth.authStateChanges().map((fUser){
     final user = fUser == null ? User.empty : fUser.toUser;
     _cache.write(key: user.id, value: user);
     return user;
    });
  }
.......
}

and create a provider to that class:

final authRepoProvider  = Provider((ref){
  return AuthRepo();
});

final authStateProvider = StreamProvider((ref){
  final result_1 = ref.read(authRepoProvider).user;
  final result_2 = ref.watch(authRepoProvider).user;

});

Both results return Stream<User>. So when using ref.read, the stream itself never changes right? maybe I am wrong but if I use ref.watch it means I stream to another stream<User>. I read the documentation several times and am still confused about how to approach this case.

CodePudding user response:

There is a red flag in the docs that says:

DON'T CALL READ INSIDE THE BODY OF A PROVIDER

final myProvider = Provider((ref) {
  // Bad practice to call `read` here
  final value = ref.read(anotherProvider);
});

If you used read as an attempt to avoid unwanted rebuilds of your object, refer to My provider updates too often, what can I do?

This includes the other providers like StreamProvider. So, just use the safer ref.watch.

If possible, avoid using read and prefer watch, which is generally safer to use.

  • Related