Difference between yield and yield* in Dart

yield

It is used to emit values from a generator either async or sync.

Example:

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

void main() {
  getStream(3).forEach(print);
}

Output:

1
2
3

yield*

It delegates the call to another generator and after that generator stops producing the values, it resumes generating its own values.

Example:

Stream<int> getStream(int n) async* {
  if (n > 0) {  
    await Future.delayed(Duration(seconds: 1));
    yield n; 
    yield* getStream(n - 1); 
  }
}

void main() {
  getStream(3).forEach(print);
}

Output:

3
2 
1 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)