코드팩토리의 플러터 프로그래밍 2판 책을 참고하여 공부용으로 작성한 게시글입니다.
📌 Stream
Stream에 주입되는 모든 값들을 지속적으로 받아온다.
반환값을 딱 한번 받아내는 Future와는 달리 지속적으로 값을 받을 수 있다.
Stream<받아오는자료형>
Stream에 .listen을 하면 받아와진다. (스트림 구독 - 단일 구독, 브로드캐스트 구독 가능)
함수에서 사용할 때,
async* 키워드로 스트림함수를 정의하고, yield 키워드로 스트림 값을 전달
StreamController로 스트림을 수동으로 생성하고 이벤트를 추가할 수 있다.
단일 값 제공
Stream<int> singleValueStream() async* {
yield 42;
}
void main() async {
singleValueStream().listen((value) {
print(value); // 42
});
}
여러 값 제공
Stream<int> multipleValuesStream() async* {
for (int i = 1; i <= 3; i++) {
yield i; // 값을 하나씩 전달
await Future.delayed(Duration(seconds: 1)); // 1초 지연
}
}
void main() async {
multipleValuesStream().listen((value) {
print(value); // 1, 2, 3 (1초 간격)
});
}
Stream.periodic(Duration객체, 비동기함수)
: 특정 시간 간격으로 이벤트를 지속적으로 발생시킨다.
void main() {
Stream<int> periodicStream = Stream.periodic(Duration(seconds: 1), (count) => count);
periodicStream.listen((value) {
print(value); // 0, 1, 2, 3, ...
if (value == 5) {
print("Stopping after 5 values");
}
});
}
listen 메서드
: 스트림 이벤트를 구독하고 처리(처리, 에러처리, 완료처리, 에러시종료처리)한다.
- onData: 데이터 이벤트를 처리. (첫번째 인자: 함수)
- onError: 에러 이벤트를 처리.
- onDone: 스트림 완료 이벤트를 처리.
- cancelOnError: 에러 발생 시 스트림을 종료할지 여부.
Stream<int> numberStream() async* {
for (int i = 1; i <= 3; i++) {
yield i;
}
}
void main() async {
numberStream().listen(
(value) {
print("Value: $value"); // Value: 1, Value: 2, Value: 3
},
onError: (error) {
print("Error: $error");
},
onDone: () {
print("Stream completed");
},
cancelOnError: false,
);
}
브로드캐스트 스트림
: 여러 리스너가 구독 가능하다.
- .asBroadcastStream()으로 변환
void main() {
Stream<int> broadcastStream = Stream.fromIterable([1, 2, 3]).asBroadcastStream();
// 여러 리스너가 구독 가능
broadcastStream.listen((value) => print("Listener 1: $value")); // Listener 1: 1, 2, 3
broadcastStream.listen((value) => print("Listener 2: $value")); // Listener 2: 1, 2, 3
}
StreamController
StreamController를 사용해 스트림을 수동으로 생성하고 이벤트를 추가할 수 있습니다.
import 'dart:async';
void main() {
final controller = StreamController<int>();
final Sink<int> input = controller.sink; //입력부분. 이렇게하는게 내부구조를 명확하게 볼 수 있음
//Stream 수동생성
final Stream<int> output = controller.stream; // 출력부분. Stream에서 데이터가져오는애
//ouput.listen과 동일
controller.stream.listen((value) {
print("Received: $value");
});
controller.add(1); //스트림에 이벤트 추가 (controller.sink.add(1)) 과 동일
input.add(1);
controller.add(2);
controller.add(3);
controller.close(); // 스트림을 닫는다.
}
#코드팩토리의플러터프로그래밍2판 #공부용
'◼️Flutter' 카테고리의 다른 글
[Dart 3.0] 구조 분해 (0) | 2025.01.25 |
---|---|
[Dart 3.0] 레코드 (0) | 2025.01.25 |
[Flutter Dart] async 와 await (0) | 2025.01.25 |
[Flutter Dart] 비동기 프로그래밍 - Future (0) | 2025.01.25 |
[Flutter Dart] 캐스케이드 연산자 '..' 키워드 (0) | 2025.01.25 |