简体   繁体   English

SwiftUI中的`Task`和`async`有什么区别

[英]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?我想知道这些和我应该使用哪一个有什么区别?

async {... } is deprecated. async {... }已弃用。 I can't even find the documentation page for the async function.我什至找不到async function 的文档页面。 It has been replaced by Task {... } , which uses this initialiser of Task .它已被Task {... }取代,它使用Task这个初始化程序

Task {... } runs an asynchronous operation as a top level task. Task {... }将异步操作作为顶级任务运行。

The .task view modifier , on the other hand, is a view modifier , and runs the asynchronous operation when the view appears .另一方面, .task视图修饰符是一个视图修饰符当视图出现时运行异步操作。 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() 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM