乐闻世界logo
搜索文章和话题

What are the different types of streams in Dart?

1个答案

1

In Dart, streams are a crucial concept for handling asynchronous event sequences. Streams can be used to read data from files or networks, process user input, and handle other asynchronous operations. Dart primarily has two types of streams: single subscription streams and broadcast streams.

1. Single subscription streams

Single subscription streams are the most common type of stream, allowing only one listener to monitor data. Once you start listening to the stream, you cannot add another listener; attempting to do so will throw an exception. These streams are ideal for scenarios requiring sequential data processing, such as file reading.

Example:

dart
import 'dart:async'; import 'dart:io'; void main() { // Open file as stream Stream<List<int>> stream = File('example.txt').openRead(); // Listen for data events stream.listen((data) { print('Received data: ${String.fromCharCodes(data)}'); }, onDone: () { print('File is now fully read.'); }, onError: (e) { print('Error occurred: $e'); }); }

2. Broadcast streams

Broadcast streams can be listened to by multiple listeners simultaneously. This type of stream is ideal for event listening, such as UI events or changes in application state. Broadcast streams do not guarantee the order in which listeners receive data, so they are typically used in scenarios where data ordering among listeners is not required.

Example:

dart
import 'dart:async'; void main() { // Create a broadcast stream controller var streamController = StreamController.broadcast(); // Listen to the stream streamController.stream.listen((data) { print('Listener 1: $data'); }); streamController.stream.listen((data) { print('Listener 2: $data'); }); // Add data to the stream streamController.add('Hello, World!'); streamController.add('Another event'); // Close the stream streamController.close(); }

Summary

When choosing between single subscription streams and broadcast streams, consider whether your application requires data ordering or multiple consumers. Each stream type has specific use cases and advantages, and selecting the appropriate one can help you process data and events more efficiently.

2024年8月5日 12:44 回复

你的答案