Task
public protocol Task : AnyObject
A task is any unit of work that is to be carried out. It is protocol based and has a main function called execute
that is called when the task is supposed to be executed. When a task is completed, a completion callback is called
and passed the result of the task, which is a Result<SuccessValue, Error>.
Timeouts
Tasks can implement a timeout that will determine when the TaskManager is to give up on the task.
Cancellation
And finally, every task has a Task.didCancel(with:) that is passed a TaskError that tells the Task object
why the task was cancelled. The didCancel will only be called after the task has been removed from the
TaskManager.
Notes
Tasks are reference types because the task manager has to keep track of all the tasks that are floating around.
-
The type of a successful execution of a task
Declaration
Swift
associatedtype SuccessValue -
Covenience typealias for the result of
executeDeclaration
Swift
typealias Result = Swift.Result<SuccessValue, Error> -
Conveneience typealias for the completion callback of
executeDeclaration
Swift
typealias CompletionCallback = (Result) -> Void -
The function that executes the task
Declaration
Swift
func execute(completion: @escaping CompletionCallback)Parameters
completionthe completion callback that the implementaiton must call when it is done with its work
-
timeoutDefault implementationHow long does is the
executefunction allowed to takeDefault Implementation
Declaration
Swift
var timeout: DispatchTimeInterval? { get } -
didCancel(with:Default implementation) -
async(using:Extension methodstartImmediately: after: queue: timeout: completion: ) Will execute the task asynchronously
Declaration
Swift
@discardableResult public func async( using taskManager: TaskManager? = nil, startImmediately: Bool = true, after interval: DispatchTimeInterval? = nil, queue: DispatchQueue? = nil, timeout: DispatchTimeInterval? = nil, completion: CompletionCallback? = nil ) -> HandleParameters
taskManagerwhich instance of
TaskManageryou want to use. Defaults toTaskManager.sharedafterafter how long you want the task to start being executed
startImmediatelyset this to false if you want to explicity call start on the
Handlethat’s returnedqueueon which DispatchQueue you want the completion callback to be called
timeoutafter how long should the task timeout. This overwrites
Task.timeoutif there is onecompletionthe reuslt of the operation will be passed here
-
await(using:Extension methodtimeout: ) Will execute the task synchronously and await the result. Throws an error on failure.
Declaration
Swift
public func await( using taskManager: TaskManager? = nil, timeout: DispatchTimeInterval? = nil ) throws -> SuccessValueParameters
taskManagerwhich instance of
TaskManageryou want to use. Defaults toTaskManager.sharedtimeoutafter how long should the task timeout. This overwrites
Task.timeoutif there is one
View on GitHub
Task Protocol Reference