Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .onAppear() and .task() in SwiftUI 3?

Tags:

swift

swiftui

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?

like image 711
Shawkath Srijon Avatar asked Sep 09 '25 18:09

Shawkath Srijon


1 Answers

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.

like image 198
Raja Kishan Avatar answered Sep 12 '25 14:09

Raja Kishan