Created with <3 with dartpad.dev.
Created
January 30, 2024 07:47
-
-
Save matifdeveloper/aed1ed594a7ba0f9855e6ff72d771bad to your computer and use it in GitHub Desktop.
Stream controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
void main() { | |
// Create a StreamController with integers | |
StreamController<int> streamController = StreamController<int>(); | |
// Create a stream from the controller | |
Stream<int> stream = streamController.stream; | |
// Add a listener to the stream | |
StreamSubscription<int> subscription = stream.listen( | |
(int data) { | |
print("Received data: $data"); | |
}, | |
onDone: () { | |
print("Stream closed"); | |
}, | |
onError: (error) { | |
print("Error: $error"); | |
}, | |
cancelOnError: false, // Set to true if you want to cancel on error | |
); | |
// Add some data to the stream | |
streamController.add(1); | |
Future.delayed(Duration(seconds: 1), (){ | |
streamController.add(2); | |
}); | |
Future.delayed(Duration(seconds: 2), (){ | |
streamController.add(3); | |
}); | |
Future.delayed(Duration(seconds: 3), (){ | |
// Close the stream when done | |
streamController.close(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment