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

Viewed 3220

It seems we can now perform same task within .onAppear() or .task in iOS15. However could not find the advantage of .task() over .onAppear(). Anyone out there can explain?

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(_:) 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.

Related