New in SwiftUI 3: Task in SwiftUI 3 and iOS 15
Task modifier was introduced in WWDC21 as part of iOS 15 release. Task modifier can be applied on any SwiftUI view and is another way(better way š) to start asynchronous task.
So, if you have been using onAppear
to fetch data when your view appears then you can use task
instead. Task modifier is more powerful and manages work state automatically so if your view unloads from memory while work is still underway, task
takes care of cancelling itself automatically.
Here is what task
function signature looks like:
func task(priority: TaskPriority = .userInitiated, _ action: @escaping () async-> Void) -> some View
TaskPriority
determines priority for the task while the async task is being created. TaskPriority
is set to userInitiated
by default so simplest task can be just a trailing closure requesting resource from remote API.
Other values for TaskPriority
are:
- high
- medium
- low
- userInitiated (this is default)
- utility
- background
action
closure is the closure that SwiftUI will call as async task when your view appears. SwiftUI will automatically cancel this task if the view disappears before async task completes.
Letās build a simple example by fetching Appleās current stock data from lil softwareās stock api. API itself is veryā¦