Search code examples
swiftswiftuiasync-await

What's the difference between `Task` and `async` in SwiftUI


So I have seen code like:

func doSomething() {
  async {
    let foo = await something()
  }
}

vs

func doSomething() {
  Task {
    await doSomething()
  }
}

There's also a modifier version of the Task:

TextView(...)
  .task {
    let foo = await something()
  }

I am wondering what's the difference between these and which one should I use?


Solution

  • async { ... } is deprecated. It has been replaced by Task { ... }, which uses this initialiser of Task.

    Task { ... } runs an asynchronous operation as a top level task.

    The .task view modifier, on the other hand, is a view modifier, and runs the asynchronous operation when the view appears. Importantly, this task has the same life time as the view. If the view gets removed, the task gets cancelled too.

    Compare:

    func foo() {
        Task {
            await doWork() // gets started when foo is called
        }
    }
    

    and

    Text("Hello")
        .task {
            // gets started when "Hello" appears,
            // *not* when .task is called
            await doWork() 
        }