It seems we can now perform same task within onAppear(action:)
or task(priority:action:)
in iOS 15. However, I could not find the advantage of task(priority:action:)
over onAppear(action:)
. Can anyone out there explain?
Both task()
and onAppear()
are the same for running synchronous functions when a view appears.
The main point difference is in the task(id:priority:_:)
task will be cancelled when this view disappears. It means when you're calling any webservice/ API or added any other task and back the screen then this task will automatically cancel.
Task is executed asynchronously and allowing you to start asynchronous work as soon as the view is shown.
Another use of task is, you can use task(id:_:)
as mention in the doc
The running task will be cancelled either when the value changes causing a new task to start or when this view disappears.
The example below shows listening to notifications to show when a user signs in.
Text(status ?? "Signed Out")
.task(id: server) {
let sequence = NotificationCenter.default.notifications(
of: .didChangeStatus, on: server)
for try await notification in sequence {
status = notification.userInfo["status"] as? String
}
}
You can read more from this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With