[英]What is the difference between .onAppear() and .task() in SwiftUI 3?
It seems we can now perform same task within.onAppear() or.task in iOS15.看来我们现在可以在 iOS15 中执行相同的任务 within.onAppear() 或 .task。 However could not find the advantage of.task() over.onAppear().
但是找不到.task() 相对于.onAppear() 的优势。 Anyone out there can explain?
有谁能解释一下吗?
Both task()
and onAppear()
are the same for running synchronous functions when a view appears. task()
和onAppear()
对于在视图出现时运行同步函数是相同的。
The main point difference is in the task(id:priority:_:)
task will be cancelled when this view disappears.主要区别在于
task(id:priority:_:)
当此视图消失时任务将被取消。 It means when you're calling any webservice/ API or added any other task and back the screen then this task will automatically cancel.这意味着当您调用任何网络服务/ API 或添加任何其他任务并返回屏幕时,此任务将自动取消。
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 task 的另一个用途是,您可以使用文档中提到的
task(id:_:)
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.