flutter

dart generator

paulaner80 2021. 9. 9. 10:36
반응형

 

import 'dart:io';

// sync* Iterable을 반환한다.
Iterable<int> coutUpGeneSync(int n) sync*{
  int k = 1;
  while(k<=n){
    yield k++;
    sleep(Duration(seconds: 1));
  }
}

// async* 사용 : Stream을 반환한다.
Stream<int> coutUpGeneAsync(int n) async*{
  int k = 0;
  while(k<n){
    yield k++;
    sleep(Duration(seconds: 1));
  }
}

// yield* : 제네레이터를 반환한다.
Iterable<int> coutUpGeneSyncRecur(int num) sync*{
  if(num>0){
    yield* coutUpGeneSyncRecur(num-1);
    yield num;
    sleep(Duration(seconds: 1));
  }
}

test1(int n){
  var gs = coutUpGeneSync(n);
  for(int v in gs){
    print(v);
  }
}

test2(int n){
  var gas = coutUpGeneAsync(n);
  gas.listen((event) {
    print(event);
  });
}


test3(int n){
  Iterable<int> sequence = coutUpGeneSyncRecur(n);

  for (int value in sequence) {
    print(value);
  }
}

void main(){
  test1(5);
  test2(5);
  test3(5);
}

'flutter' 카테고리의 다른 글

bloc timer  (0) 2021.09.30
dart future then  (0) 2021.04.09
Provider 예제  (0) 2021.04.08
dart functor  (0) 2020.12.28
flutter - firebase 로그인, 로그아웃  (0) 2020.12.21