Streams trong Dart
1. Giới thiệu
Stream là chuỗi các sự kiện bất đồng bộ theo thời gian, khác với Future chỉ có một giá trị.
2. Tạo Stream từ Iterable
void main() async {
var stream = Stream.fromIterable([1, 2, 3, 4, 5]);
await for (var value in stream) {
print(value);
}
}3. Tạo Stream với async*
Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() async {
await for (var count in countStream(5)) {
print(count);
}
}4. Stream Controller
import 'dart:async';
void main() async {
var controller = StreamController<int>();
// Listen to stream
controller.stream.listen(
(data) => print('Received: $data'),
onError: (error) => print('Error: $error'),
onDone: () => print('Done'),
);
// Add data
controller.sink.add(1);
controller.sink.add(2);
controller.sink.add(3);
await controller.close();
}5. Broadcast Stream
void main() {
var controller = StreamController<int>.broadcast();
// Nhiều listeners
controller.stream.listen((data) => print('Listener 1: $data'));
controller.stream.listen((data) => print('Listener 2: $data'));
controller.add(1);
controller.add(2);
}6. Stream Transformations
void main() async {
var stream = Stream.fromIterable([1, 2, 3, 4, 5]);
// map
await stream.map((n) => n * 2).forEach(print);
// 2, 4, 6, 8, 10
// where (filter)
var stream2 = Stream.fromIterable([1, 2, 3, 4, 5]);
await stream2.where((n) => n % 2 == 0).forEach(print);
// 2, 4
// take
var stream3 = Stream.fromIterable([1, 2, 3, 4, 5]);
await stream3.take(3).forEach(print);
// 1, 2, 3
}7. Stream với Timer
Stream<int> timerStream() {
return Stream.periodic(
Duration(seconds: 1),
(count) => count,
).take(5);
}
void main() async {
await for (var count in timerStream()) {
print('Tick: $count');
}
}8. StreamBuilder trong Flutter
StreamBuilder<int>(
stream: countStream(10),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return Text('Count: ${snapshot.data}');
},
)9. Combine Streams
void main() async {
var stream1 = Stream.fromIterable([1, 2, 3]);
var stream2 = Stream.fromIterable([4, 5, 6]);
// Concat
var combined = StreamGroup.merge([stream1, stream2]);
await combined.forEach(print);
}10. Xử lý lỗi
void main() {
var controller = StreamController<int>();
controller.stream.listen(
(data) => print('Data: $data'),
onError: (error) => print('Error: $error'),
cancelOnError: false, // Tiếp tục sau lỗi
);
controller.add(1);
controller.addError('Something went wrong');
controller.add(2); // Vẫn nhận được
}📝 Tóm tắt
- Stream là chuỗi sự kiện bất đồng bộ
async*vàyieldtạo streamStreamControllerquản lý streambroadcastcho nhiều listeners- Transformations: map, where, take, skip
await forđể consume stream
Last updated on