Bad state: cannot emit new states after calling close

A “bad state: cannot emit new states after calling close” error typically occurs when you are trying to modify or emit new states in a closed or finalized function or method.

This error commonly occurs when dealing with asynchronous operations or when using streams in programming languages like JavaScript or Dart.

For example, consider the following Dart code:


Stream<int> getNumbers() async* {
  for (int i = 0; i < 5; i++) {
    yield i;
  }
}
  
void main() async {
  final stream = getNumbers();
  
  stream.listen((value) {
    print(value);
  }).onDone(() {
    stream.close(); // Closing the stream
  });
  
  await for (int number in stream) { // Trying to iterate over closed stream
    // Do something with number
  }
}

    

In this example, a stream of numbers is created using a generator function. The listener is added to the stream and the function `onDone()` is called when the stream finishes emitting values. In the `onDone()` callback, the stream is closed using the `close()` method.

However, after closing the stream, the code tries to iterate over the closed stream using a `for` loop. This is not allowed and results in the “bad state: cannot emit new states after calling close” error.

To fix this error, you need to ensure that you do not attempt to emit new states or iterate over a closed stream. This can be done by restructuring your code to avoid using the stream after it has been closed.

Read more interesting post

Leave a comment