ConcurrentDispatchQueueScheduler

In this example, we are starting out on the main thread. First, we will create an imageData PublishSubject of type data. We will be adding the Swift and Rx image data values onto this sequence later on. Next, we will create a concurrentScheduler by making use of the ConcurrentDispatchQueueScheduler convenience initializer, which takes a Quality of Service (QoS) enum and sets that to the background, as follows:

let imageData = PublishSubject<Data>()
let concurrentScheduler = ConcurrentDispatchQueueScheduler(qos: .background)

Now we will use ObserveOn to indicate that we want events received from the sequence on the concurrentScheduler we created, and we will use map to transform that data into a UIImage instance, as follows:

imageData
.observeOn(concurrentScheduler)
.map { UIImage(data: $0) }

By doing this work on a background queue, we are ensuring peak performance on the main thread. However, once we have a UIImage, we need to go back to the main thread in order to display it, so we will use ObserveOn again, this time passing in the MainScheduler Singleton instance. Then, we will subscribe(onNext) to set the image on the imageView, and finally we will add the subscription to the disposeBag, as shown:

imageData
.observeOn(concurrentScheduler)
.map { UIImage(data: $0) }
.observeOn(MainScheduler.instance)
.subscribe(onNext: {
imageView.image = $0
})
.disposed(by: disposeBag)

Although we are observing on the main thread here, we do want to mention that disposeBag is thread-safe. If we were creating a subscription on a different thread, it would be okay to add that subscription to this disposeBag. Now we will add the Swift imageData to the imageData sequence:

imageData.onNext(swiftImageData)

Now, observe that the imageView displays the Swift image as shown here:

Now, we will add the rxImageData onto the image data subject, as follows:

imageData.onNext(rxImageData)

Also, see the Rx image displayed, as follows:

That was an example of using a global concurrent dispatch queue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset