Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] Update key generation for adding handlers #13

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions Receiver/Sources/Receiver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ public class Receiver<Wave> {

private let values = Atomic<[Wave]>([])
private let strategy: Strategy
private let handlers = Atomic<[Int:Handler]>([:])
private let handlers = Atomic<[UInt64:Handler]>([:])
private var nextKey: UInt64 = 0

private init(strategy: Strategy) {
self.strategy = strategy
Expand Down Expand Up @@ -105,12 +106,12 @@ public class Receiver<Wave> {
/// a new value is sent.
/// - returns: A reference to a disposable
@discardableResult public func listen(to handle: @escaping (Wave) -> Void) -> Disposable {
var _key: Int!
handlers.apply { _handlers in
_key = (_handlers.keys.map { $0.hashValue }.max() ?? -1) + 1
_handlers[_key] = handle
}

var _key: UInt64!
handlers.apply { _handlers in
_key = nextKey
_handlers[_key] = handle
nextKey = nextKey &+ 1
}
switch strategy {
case .cold:
broadcast(elements: Int.max)
Expand Down
33 changes: 33 additions & 0 deletions ReceiverTests/ReceiverTests+Performance.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,37 @@ class ReceiverTests_Performance: XCTestCase {
}
}
}

func test_listen_and_dispose_performance() {
self.measure {
let numberOfListeners = 10000
var numberOfDisposes = 0
let (transmitter, receiver) = Receiver<Int>.make()
var called = 0
var disposables = [Disposable]()

for i in 1...numberOfListeners {

let disposable = receiver.listen { wave in
XCTAssertTrue(wave == 1)
called = called + 1
}

disposables.append(disposable)

if i % 3 == 0 && disposables.count > 0 {
let d = disposables.remove(at: Int.random(in: 0..<disposables.count))
d.dispose()
numberOfDisposes += 1
}
}

transmitter.broadcast(1)
XCTAssertEqual(called, numberOfListeners-numberOfDisposes)

transmitter.broadcast(1)
XCTAssertEqual(called, (numberOfListeners-numberOfDisposes)*2)
}
}

}