What are the advantages of using StreamBuilder compared to Stream.listen()
void _authStateChanges() {
FirebaseAuth.instance.authStateChanges().listen(
(user) {
appNotifier.setUser(user);
if (_isInitializing) {
// first loading: show CircularProgress
_isInitializing = false;
notifyListeners();
}
},
onDone: () {
debugPrint("event onDone");
},
one rror: (e, s) {
debugPrint("event one rror $e");
},
);
}
What would be the advantages compared to StreamBuilder, if it is better to handle the reconstruction?
CodePudding user response:
StreamBuilder
's approach is better because
Stream#listen
returns a stream subscription, which needs to be cancelled when you've done using it (otherwise it'll be a memory leak). When you useStreamBuilder
, the stream subscription is automatically disposed, so you dont have to handle it.In your
Stream#listen
approach, you have to store two additional variables: the stream subscription, so you can cancel it later, and another field to check if it's loaded or not (in your case,_isInitializing
). If you useStreamBuilder
, you don't need any additional fields (in some cases, you'll need to store the stream, but nothing more than that).
Either way, a StreamBuilder
is an abstraction for Stream#listen
if you look at source code.
CodePudding user response:
In my opinion it totally depends on the functionality of the application. In some instances such as for a UserModel
, you would want to use a Stream#listen
since it will keep listening to any changes in the said model. Whereas, the StreamBuilder
will only listen when you are in that particular class and dispose off immediately after leaving that class.
User stream is such that you would be increasing the reads of your database since you have to utilize it more or less through out the code so calling it at the start of the application and disposing it off at the log out is a better approach as it will not create more reads.
So in short, it really depends upon the usage and functionality of the application.