To work with the operation queue API instead of GCD, first we need to create an OperationQueue instance and then create an OperationQueueScheduler with that operation queue, as follows:
let opQueue = OperationQueue()
let opQueueScheduler = OperationQueueScheduler(operationQueue: opQueue)
Finally, we can use the opQueueScheduler instead of the serial queue scheduler with theĀ ObserveOn operator, as demonstrated:
imageData
.observeOn(opQueueScheduler)
.map { UIImage(data: $0) }
.observeOn(MainScheduler.instance)
.subscribe(onNext: {
imageView.image = $0
})
.disposed(by: disposeBag)
The overall code for this demonstration can be summarized as follows:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
import RxSwift
let imageView = UIImageView(
frame: CGRect(
x: 0,
y: 0,
width: 128,
height: 128
)
)
PlaygroundPage.current.liveView = imageView
let swift = UIImage(named: "Swift")!
let swiftImageData = UIImagePNGRepresentation(swift)!
let rx = UIImage(named: "Rx")!
let rxImageData = UIImagePNGRepresentation(rx)!
let disposeBag = DisposeBag()
let imageData = PublishSubject<Data>()
let concurrentScheduler = ConcurrentDispatchQueueScheduler(qos: .background)
let conQueue = DispatchQueue(label: "com.Navdeep.conQueue", attributes: .concurrent)
let serScheduler = SerialDispatchQueueScheduler(queue: conQueue, internalSerialQueueName: "com.Navdeep.serQueue")
let opQueue = OperationQueue()
let opQueueScheduler = OperationQueueScheduler(operationQueue: opQueue)
imageData
.observeOn(opQueueScheduler)
.map { UIImage(data: $0) }
.observeOn(MainScheduler.instance)
.subscribe(onNext: {
imageView.image = $0
})
.disposed(by: disposeBag)
imageData.onNext(swiftImageData)
imageData.onNext(rxImageData)