Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
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 31
Archives
Today
Total
관리 메뉴

JunHyeok

[Flutter] 4. Future - async 심화학습 -by 코딩셰프 본문

Flutter/조금매운맛

[Flutter] 4. Future - async 심화학습 -by 코딩셰프

junhyeok-log 2024. 6. 14. 13:57

최고!

 

간단한 Future 예제

void main() {
  print('Before Future');

  Future(() {
    print('running the future');
  }).then((_) {
    print('future is complete');
  });
  print('after future');
}

 

결괏값

Before Future
after future
running the future
future is complete

 

 

위처럼, Future는 순차적으로 진행되지 않으며, Event Queue 에서 선입 선출로 실행됩니다.

 

 

Async method

  1. 메서드를 통해서 나오는 결과들은 future 가 됩니다.
  2. await 키워드를 만날때까지 synchronous 방식으로 동작합니다.
  3. await 키워드를 만나면, Future가 완료될 때 까지 대기합니다.
  4. future가 완료되자마자 그 다음 코드들을 실행합니다.

 

 

 

미완성 비동기 코드

String createOrderMessage() {
  var order = fetchUserOrder();
  return 'Your order is $order';
}

Future<String> fetchUserOrder() {
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Large Latte',
  );
}

void main() {
  print("주문할게용");
  print("Fetching user order");
  print(createOrderMessage());
}

 

출력

주문할게용
Fetching user order
Your order is Instance of '_Future<String>'

 

 

비동기적으로 Future<String> 타입을 받아와야 하지만, async - await 처리를 하지 않아서 모든 코드가 직렬적으로 실행되며 종료됩니다.

 

이 부분을 어떻게 해결할 수 있을까요?

 

 

 

async - await 처리

 

Future<String> createOrderMessage() async {
  print('라떼 만들러갑니다');
  var order = await fetchUserOrder();
  return 'Your order is $order';
}

Future<String> fetchUserOrder() {
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Large Latte',
  );
}

void main() async {
  print("Fetching user order");
  print( await  createOrderMessage());
  print("라떼 나왔다구");
}

 

과정

  1. main 함수에 async 키워드를 넣은 뒤 await 처리를 해주면, createOrderMessage() 함수가 끝난 다음, print("라떼 나왔다구") 라는 코드가 실행됨을 보장합니다.
  2. 이와 같이, createOrderMessage() 함수 또한 fetchUserOrder 함수에서 string 값이 반환되는 것을 기다립니다.
  3. 마지막으로 아래와 같은 결과를 얻을 수 있습니다.

 

결과

Fetching user order
라떼 만들러갑니다
Your order is Large Latte
라떼 나왔다구

 

 

 

조금? 복잡한 예제

 

void main() async {
  methodA();
  await methodB();
  await methodC('main');
  methodD();
}

methodA() {
  print('A');
}

methodB() async {
  print('B start');
  await methodC('B');
  print('B end');
}

methodC(String from) async {
  print('C start from $from');

  Future(() {
    print('C running future from $from');
  }).then((_) {
    print('C end of Future from $from');
  });

  print('C end from $from');
}

methodD() {
  print('D');
}

 

 

Event Loop는 동기적 코드가 모두 실행된 후에 async 작업을 처리하기 때문에 아래와 같은 결과로 출력이 됩니다!

 

A
B start
C start from B
C end from B
B end
C start from main
C end from main
D
C running future from B
C end of Future from B
C running future from main
C end of Future from main