How to close StreamProvider with Riverpod in Flutter
1,659
You refer below sample.
final example = StreamProvider.autoDispose((ref) {
final streamController = StreamController<int>();
for(int i=0; i<=5 ; i++){
// read stream values like this might help
streamController.stream.last.then((value) => {if(value==5)
{streamController.close()}});
if(!streamController.isClosed) {
streamController.add(i);
}
}
ref.onDispose(() {
// Closes the StreamController when the state of this provider is destroyed.
streamController.close();
});
return streamController.stream;
});
Refer the document for more info https://riverpod.dev/docs/concepts/providers
Author by
Idan Ber
Updated on December 26, 2022Comments
-
Idan Ber over 1 year
I'm using Riverpod StreamProvider.
And i would like to know 2 things:
1 - I've learned from a youtube video about stream providers and the code the guy in the video coded something like that:
final streamProvider = StreamProvider.autoDispose<int>((ref) { return Stream.periodic(Duration(seconds: 1), (number) { if (number < 5) return number + 1; else { return 5; } }); });
The question is: from my understanding using a stream method will require me to use "async*", so why there is no need here?
2 - How can i make sure once the stream's number value is equal to 5 the stream provider will close and stop updating the UI?
Thank you so much!
-
Idan Ber over 3 yearsHey chain, i've seen it but how can i use it to close the Stream when number=5. Still did not get it :(
-
chain over 3 yearsHey @IdanBer, check out the edited answer. That might help you.
-
Idan Ber over 3 yearsHey @chain, thats awsome!, much appriciated, i'll try it and let you know if everything works properly.