티스토리 뷰

반응형

밑의 두 자료를 참고하여 나름대로 정리해보았다. 

https://dart.dev/tutorials/language/streams

 

Asynchronous programming: Streams

Learn how to consume single-subscriber and broadcast streams.

dart.dev

https://stackoverflow.com/questions/55397023/whats-the-difference-between-async-and-async-in-dart

 

What's the difference between async and async* in Dart?

I am making an application using flutter framework . During this I came across with the keywords in Dart async and async*. Can anybody tell me what's the difference between them?

stackoverflow.com

 

 

async

: You add the async keyword to a function that does some work that might take a long time. It returns the result wrapped in a Future.

Future<int> doSomeLongTask() async {
  await Future.delayed(const Duration(seconds: 1));
  return 42;
}

async*

: You add the async* keyword to make a function that returns a bunch of future values one at a time. The results are wrapped in a Stream.

Stream<int> countForOneMinute() async* {
  for (int i = 1; i <= 60; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
  }
}

You use yield to return a value instead of return because you aren't leaving the function.

You can use await for to wait for each value emitted by the Stream.

main() async {
  await for (int i in countForOneMinute()) {
    print(i); // prints 1 to 60, one integer per second
  }
}

 

아래의 코드는 Dart 공식 홈페이지에서의 예제이다. 

Future<int> sumStream(Stream<int> stream) async {
  
  var sum =0;
  await for (var value in stream) {
    sum +=value;
  }
  
  return sum;
}

Stream<int> countStream(int to) async* {
  
  for (int i =1; i<=to; i++) {
    yield i;
  }
}

Future<void> main() async{
  var stream = countStream(10);
  var sum = await sumStream(stream);
  print(sum);
}
반응형

'개발 > Flutter' 카테고리의 다른 글

Flutter UDP 참고자료들  (0) 2021.07.22
Firebase 연동 에러 해결  (0) 2021.07.22
DatetimeRange Flutter & showDateRangePicker Flutter  (0) 2021.07.14
Onpressed: null  (0) 2021.07.14
final vs const  (0) 2021.06.28
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함