Skip to content

Instantly share code, notes, and snippets.

@shoumikhin
Last active February 5, 2018 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoumikhin/a3234c2c2801396051a0991992feb3cf to your computer and use it in GitHub Desktop.
Save shoumikhin/a3234c2c2801396051a0991992feb3cf to your computer and use it in GitHub Desktop.
import RxSwift
import XCTest
/// Measures the average time needed to create a `BehaviorSubject`, chain three `do` blocks on
/// it and get into the last `subscribe` block.
func testRxSubscribeOnSerialQueue() {
// Arrange.
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = Constants.iterationCount
let queue = DispatchQueue(label: #function, qos: .userInitiated)
let semaphore = DispatchSemaphore(value: 0)
let scheduler = SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: #function)
let disposeBag = DisposeBag()
// Act.
DispatchQueue.main.async {
let time = dispatch_benchmark(Constants.iterationCount) {
BehaviorSubject(value: true).observeOn(scheduler).do(onNext: { _ in }).do(onNext: { _ in
}).subscribe(onNext: { _ in
semaphore.signal()
expectation.fulfill()
}).disposed(by: disposeBag)
semaphore.wait()
}
print(average: time)
}
// Assert.
waitForExpectations(timeout: 10)
}
/// Measures the total time needed to observe a lot of `PublishSubject` with chained `subscribe`
/// blocks on them on a concurrent queue and wait for each of them to get into chained block.
func testRxSubscribeOnConcurrentQueue() {
// Arrange.
let queue = DispatchQueue(label: #function, qos: .userInitiated, attributes: .concurrent)
let group = DispatchGroup()
let scheduler = ConcurrentDispatchQueueScheduler(queue: queue)
let disposeBag = DisposeBag()
var subjects = [PublishSubject<Bool>]()
for _ in 0..<Constants.iterationCount {
group.enter()
let subject = PublishSubject<Bool>()
subject.observeOn(scheduler).subscribe(onNext: { _ in
group.leave()
}).disposed(by: disposeBag)
subjects.append(subject)
}
let startDate = Date()
// Act.
for subject in subjects {
subject.onNext(true)
}
// Assert.
XCTAssert(group.wait(timeout: .now() + 1) == .success)
let endDate = Date()
print(total: endDate.timeIntervalSince(startDate))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment