Search code examples
flutterdartdart-async

Will forEach leak in a Dart's Broadcast Stream?


I have a StreamController.broadcast() which I pass its Steam to many of my Flutter Widgets at creation.

Since at each build I will be recreating those Widgets, I wonder if using Stream.forEach() inside those Widgets won't lead to memory leaks, as forEach() has no mechanism to close the Subscription. I wonder if maybe those Subscription object won't get cleaned-up, or even if the Widgets themselves won't get out of memory.


Solution

  • Yes, it will.

    The listener is maintained until the stream ends or emits an error.

    So if you do Stream.forEach inside build, then any rebuild of the widget will add a listener without removing the previous one.