[Flutter] Future에 대해 알아보자

mason.98·2023년 5월 2일
0

Flutter

목록 보기
5/8

Dart의 Future는 지금은 없지만 미래에 요청한 데이터 혹은 에러가 담길 그릇이다.
Future는 싱글스레드 환경에서 비동기처리를 위해 존재한다.

예시

Future<String> helloWorld() {
return Future<String>.delayed(Duration(seconds: 3), () {
    return "success";
  });
} 
...

final str = helloWorld();

str.then((val) {
	print("HelloWorld");
}).catchError((error) {
	print("ERROR!!!");
});
print("wait...");

Future<String>의 뜻은 나중에 String 혹은 error가 나온다는 이야기이다.
-> then, catchError 함수로 컨트롤할 수 있다.

Future<String>Future 에서 String으로 바뀌는 것이 아니라,
계속해서 Future<String>이다.

출력

wait...
HelloWorld

async/await

  1. await 키워드를 사용한 함수는 무조건 async 함수이어야 함.
  2. async 함수는 무조건 Future를 반환해야 함.
  3. await 을 만나면 함수를 잠시 멈추고 함수를 호출한 곳에 Future 를 return 함.
  4. await 가 붙은 동작이 완료되기 전까지 함수를 더 이상 진행하지 않음.
  5. return 을 통해 2번에서 주었던 Future 에서 return 값 반환.

예시

Future<String> HelloWorld() async {
	... await Func1();
    ... await Func2();
    return "HelloWorld";
}

final str = await HelloWorld();
  1. HelloWorld() 함수 실행.
  2. str 변수에는 Future가 담김.
  3. Func1(), Func2() 순차적으로 실행한 후에 HelloWorld return 함.
  4. str 변수에는 HelloWorld가 담김.

then() VS async/await

  • then() 함수는 수행 중인 함수를 중간에 멈추도록 하지 않음.
    따라서 해당 동작 이후 코드는 계속 실행.
  • async/await 키워드는 수행 중인 함수를 중간에 동작이 완료될 때까지 멈춤.
    따라서 해당 동작 이후 코드는 동작 완료 전까지 실행되지 않음.

async/await 예시

// Func1
Future<String> func1() {
  return Future.delayed(Duration(seconds: 3), () {
      return "1";
    });
}
// Func2
Future<String> func2() {
  return Future.delayed(Duration(seconds: 3), () {
      return "2";
    });
}
// Func3
Future<String> helloWorld() async{
	final hello1 = await func1();
    print("$hello1"); // print
    
    final hello2 = await func2();
    print("$hello2"); // print
    
    print("제일 빨리 출력하고픔"); // print
}

final helloworld = helloWorld();
print("first"); // print

async/await 출력

first // 0초
1 // 3초
2 // 6초
제일 빨리 출력하고픔 // 6초
  1. helloworld 변수 자체가 await이 아니므로 비동기처리로 first 출력.
  2. helloWorld() 함수 실행
  3. func1() 함수 끝날 때까지 대기
  4. 3초 후, 1 출력
  5. await func2() 함수 끝날 때까지 대기
  6. 3초 후, 2, 제일 빨리 출력하고픔 출력

제일 빨리 출력하고픔은 앞에 있는 await 때문에 값을 참조하지 않음에도 불구하고 가장 마지막에 실행되었다.


then() 예시

// Func1
Future<String> hello1() {
  return Future.delayed(Duration(seconds: 3), () {
      return "1";
    });
}
// Func2
Future<String> hello2() {
  return Future.delayed(Duration(seconds: 3), () {
      return "2";
    });
}
// Func3
Future<String> helloWorld() {
	final hello1 = hello1();
	hello1.then((val) => print("$val")); // print

	final hello2 = hello2();
    hello1.then((val) => print("$val")); // print
    
    print("제일 빨리 출력하고픔"); // print
}

final helloworld = helloWorld();
print("first"); // print

then() 출력

제일 빨리 출력하고픔 // 0초
first // 0초
1 // 3초
2 // 6초

대부분의 경우 asyc/await으로 대체가 되지만,
위와 같은 경우에는 then() 키워드를 사용할 수 있다.
따라서 async/await으로 완전히 대체하지는 못하지만 대부분을 대체할 수 있다.

출처
1

profile
wannabe---ing

0개의 댓글