Skip to content

Commit

Permalink
Fixes leak and Socket.disconnect() not calling onClose (davidstump#112)
Browse files Browse the repository at this point in the history
* Fix Socket.disconnect not calling onClose

Since connection.delegate is nil'd out, the Socket wasn't getting the
`websocketDidDisconnect(socket:error:)` delegate message so it'd never
call onClose callbacks.

This also fixes an issue where the Socket would never be deinit'd
because the current run loop had a strong reference to it (via the
heartbeatTimer)

* Stop timer & fire onClose directly

instead of relying on the `onConnectionClosed()` function.
`onConnectionClosed()` does some additional things that we don't want
(i.e. starting the reconnect timer) to happen when a Socket is
explicitly disconnected.

* Add tests for disconnect() calling onClose
  • Loading branch information
darrenclark authored and dsrees committed Aug 30, 2018
1 parent e300027 commit ade5c27
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Sources/Socket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ public class Socket {
public func disconnect(_ callback: (() -> Void)? = nil) {
connection.delegate = nil
connection.disconnect()

self.heartbeatTimer?.invalidate()
self.onCloseCallbacks.forEach( { $0() } )

callback?()
}
Expand Down
12 changes: 12 additions & 0 deletions Tests/SocketSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ class SocketSpec: QuickSpec {
expect(fakeConnection.delegate).to(beNil())
expect(callbackCalled).to(beTrue())
})

it("should fire onClose", closure: {
var onCloseCallsCount = 0
var onCloseCalled: Bool { return onCloseCallsCount > 0 }

socket.onClose(callback: {
onCloseCallsCount += 1
})
socket.disconnect()

expect(onCloseCalled).to(beTrue())
})
}

describe(".connect()") {
Expand Down

0 comments on commit ade5c27

Please sign in to comment.