I am very confused about how actually the StreamController is implemented in dart.
So tell me if this code cause any memory leaks.
class Backend{
final streams = <int,StreamController>{};
final ws;
StreamHandler(this.ws){
listenToWebSocket();
}
listenToWebSocket(){
ws.listen((e){
streams[e['index']].add(e['data']);
});
}
getStream(int index){
var s = StreamController();
streams[index] = s;
return s.stream;
}
}
Backend listens to the websocket and passes its data to the stream appropriate index.
class StreamListenerHandler{
Map<int,StreamListener> listeners = {};
addListener(int index){
map[index] = listeners;
}
}
class StreamListener{
final int index;
StreamListener(this.index){
startListening();
}
startListening(){
getIt<Backend>().getStream().listen((data){
//do stuff
});
}
}
StreamListener wants the websocket data. StreamListenerHandler stores the listeners.
(for those who don't know getIt package just accesses the global singleton type thing.)
so what happens if...
void main(){
var handler = StreamListenerHandler();
handler.addListener(5);
// after some time...
handler.addListener(5);
}
here on the first call of addListener a StreamListener is created and it recieves a fresh stream from the Backend.
here is my expectation about the second call...
the StreamListenerHandler replaces the current StreamListener with a new one. Then the new StreamListener calls Backend and gets a fresh stream. The old streamController has no references so it's disposed. For the old StreamListener, the reference in the StreamListenerHandler is lost and also as the old streamController is gone the listen callback is also worthless, so it will be disposed.
So I am closing nothing just removing the references. Will this cause memory wastage?
does the garbage collector calls close on the controller or just disposing the object is enough?
(I am asking all this because all over the internet people are saying you should close the streams. I don't like the "should". I want to do it only if it "required")