Memory Leaking when stopping and creating new HubConnection
kivr opened this issue · 3 comments
I am trying to stop and then reconnect using another access token several times during the app execution.
I noticed that each time I reconnect, some extra memory is taken. The way I reconnect is by calling messengerHubConnection.stop()
and then reassigning the variable as messengerHubConnection = HubConnectionBuilder(url: URL(string: "\(url)")!).withHttpConnectionOptions(configureHttpOptions: {(options) -> Void in options.accessTokenProvider = {() -> String? in token}}).withLogging(minLogLevel: .error).build()
Could you please if this is the expected way to reconnect? If that is the case then I think there is a memory leak when stopping the HubConnection.
Since I am working in a NetworkExtension, the leaked memory pile up until the extension crashes due to memory limits.
The way you reconnect should work. Because you override the messengerHubConnection
variable it should result in releasing the previous instance. If you turn on logging at the .debug
level you should see a message indicating that the previous hub connection was de-initialized:
If you don't see this message it would mean something is preventing from releasing this object (i.e. a memory leak). It can be something internal (which would be a bug) or can be introduced by creating a retain cycle in non-framework code (e.g. storing a reference to HubConnection in a completion or event handler).
Here is an article that discuss how to debug retain cycles which can help pinpoint the issue: https://iosmith.com/retain-cycles-in-swift/
@kivr That's your mistake.
when you reconnect, you always new instance from memory but not release !!!so that you will memory leak. You should do like this. @kivr
if (self.hubConnection != nil) {
self.hubConnection = nil
}
self.hubConnection = HubConnectionBuilder(url: url)
.withHttpConnectionOptions(configureHttpOptions: { (httpConnectionOptions) in
if let header = headers {
httpConnectionOptions.headers = header
}
}).withLogging(minLogLevel: .debug)
.build()
self.hubConnection?.delegate = self
self.hubConnection?.start()