Parallel Programming with Swift — Part 4/4

Block Operation, Asynchronous Operation and passing data between operations

Aaina jain
Swift India
2 min readDec 10, 2018

--

Credit: freepik.com

This article is part 4 of Parallel Programming with Swift Series. In Part 1, we looked into Dispatch Queue and system provided queues. In Part 2, we focused on another way of defining tasks and powerful APIs provided by GCD. In Part 3, we looked into Operation and Operation Queue. In this post let’s create operation and add it to Operation queue.

If you want to have a look on all parts of series:

Concurrency & GCD — Parallel Programming with Swift — Part 1/4

GCD — Parallel Programming with Swift — Part 2/4

Operations and Operation Queue Overview — Parallel Programming with Swift — Part 3/4

Block Operation and Custom Operation — Parallel Programming with Swift — Part 4/4

Block Operation:

An operation that manages the concurrent execution of one or more blocks. BlockOperation class extends from Operation class. You can use this object to execute several blocks at once without having to create separate operation objects for each. When executing more than one block, the operation itself is considered finished only when all blocks have finished executing.

Blocks added to a block operation are dispatched with default priority to an appropriate work queue.

An operation can be execute on completion of the specified operation by using addDependency method.

NSInvocationOperation:

In objective C we can create NSInvocationOperation while it’s not available in Swift.

Asynchronous Operation:

Asynchronous operations can be created by subclassing Operation class.

.

Pass data between operations:

There are various approaches to pass data between operations. Mostly adopted one is adapter pattern. Here you create new BlockOperation to pass data. This article shows all approaches in a nice way.

https://marcosantadev.com/4-ways-pass-data-operations-swift/

Benefits of using Operations over Grand Central Dispatch:

Dependency: Operations provides API to add dependency between operations which enables us to execute tasks in a specific order. An operation is ready when every dependency has finished executing.

Observable: Operations and OperationQueue has a lot of properties that can be observed using KVO.

State of Operation: You can monitor the state of an operation or operation queue. ready , executing or finished

Control: You can Pause, Cancel and Resume an Operation.

Max Number of Concurrent Operation: You can specify the maximum number of queued operations that can run simultaneously. Serial operation queue can be created by maxConcurrentOperationCount to 1.

Thanks for reading article.

You can catch me at:

Linkedin: Aaina Jain

Twitter: __aainajain

--

--