플러터 공부/코드팩토리 인강 기록
플러터 - 비동기 처리(Future, Async, Await)
Lee_SH
2023. 6. 12. 20:40
Future
지금 당장 특별한 데이터를 가지지는 않지만 미래에 어떤 타입의 데이터가 들어올것을 약속해주는 변수
예를들어 우리가 햄버거를 주문한다면 지금당장 햄버거를 가지고 있지는 않지만 주문 영수증을 통해 미래에 햄버거를 받게 된다는 것을 약속 할 수 있다. Future또한 이와 마찬가지로 제네릭<>으로 선언한 타입의 데이터를 미래에 받을것임을 약속하는것
- 비동기 작업을 할 떄 사용
- 일정 소요 시간 이후에 적절한 데이터나 에러를 반환
Await
- synchronous(동기)
- 데이터의 요청과 결과가 한 자리에서 동시에 일어나는것
- 요청을 하면 시간이 얼마나 걸리던 무조건 요청한 자리에서 결과가 주어져야한다.
- A라는 일의 요청이 들어오면 해당 요청이 끝날 때 까지 다른 일을 할 수 없기 떄문에 B라는 요청을 처리 하기 위해서 A가 끝날때까지 기다려야만한다.
- asynchronous(비동기)
- 데이터의 요청과 결과가 동시에 일어나지 않는다는것
- A라는 일을 요청 한 뒤 응답을 기다리는것이 아니라 B라는 새로운 요청을 보내거나 다른 일을 할 수 있다.
import 'dart:io';
void main(){
showData();
}
void showData(){
startTask();
String? account = accessData();
fetchData(account);
}
void startTask(){ // - 1
String info1 = '요청수행 시작';
print(info1);
}
String? accessData(){ // - 2
String? account;
Duration time = Duration(seconds: 3);
if(time.inSeconds > 2) {
// sleep(time);
Future.delayed(time, (){
account = '8,500만원';
print(account);
});
}else{
String info2 = '데이터를 가져왔습니다';
print(info2);
}
return account;
}
void fetchData(String? account){ // - 3
String info3 = '잔액은 $account 입니다';
print(info3);
}
- startTask() 실행
- accessData() 실행 time.seconds가 3이므로 조건문에 의해 Future.delayed 실행, 이때 3초간 딜레이가 걸리게 되고 그동안 fetchData()가 실행
- fetchData()가 끝나고 3초의 딜레이가 끝난 accessData()의 Future.delayed의 함수 실행
fetchData()는 accessData()의 리턴값을 받아서 실행되야하는 함수인데 현재 코드에서는 fetchData()가 먼저 실행 되기 때문에 값을 받지 못해서 결과값으로 null을 출력하게된다.
import 'dart:io';
void main() {
showData();
}
void showData() async {
startTask();
String? account = await accessData();
fetchData(account);
}
void startTask() { // - 1
String info1 = '요청수행 시작';
print(info1);
}
Future<String?> accessData() async {
String? account;
Duration time = Duration(seconds: 3);
if (time.inSeconds > 2) {
// sleep(time);
await Future.delayed(time, () {
account = '8,500만원';
print(account);
});
} else {
String info2 = '데이터를 가져왔습니다';
print(info2);
}
return account;
}
void fetchData(String? account) {
String info3 = '잔액은 $account 입니다';
print(info3);
}
- startTask() 실행
- accessData() 실행 time.seconds가 3이므로 조건문에 의해 Future.delayed 실행, 이때 3초간 딜레이가 걸리게 되지만 await으로 실행이 끝날떄까지 기다려준다.
- 이후 fetchData()가 실행
await을 사용하여 fetchData() 이전에 accessData()가 실행되도록 기다려주기때문에 순서를 강제하여 원하는 결과값을 얻는것을 볼 수 있다.
InitState 비동기 처리
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
});
InitState 비동기 처리원래 initState는 비동기 안되는데 위와같이 처리해주면 initState안에서 비동기 처리 가능
출처 - 코딩셰프 유튜브
https://www.youtube.com/watch?v=oFXV4qSXNVs