task(id:priority:_:)
聲明
func task<T>(
id value: T,
priority: TaskPriority = .userInitiated,
_ action: @escaping () async -> Void
) -> some View where T : Equatable
返回值
在視圖出現之前異步運行指定操作的視圖,或使用 id
值更改重新啟動任務。
參數
id
觀察變化的值。該值必須符合
Equatable
priority
創建異步任務時使用的任務優先級。默認優先級為
userInitiated
action
SwiftUI 在視圖出現之前作為異步任務調用的閉包。 SwiftUI 可以在視圖消失後在動作完成前自動取消任務。如果
id
值更改,SwiftUI 取消並重新啟動任務。
詳述
此方法的行為類似於 View/task(priority:_:)
,不同之處在於它還會在指定值更改時取消並重新創建任務。為了檢測更改,修改器會測試 id
參數的新值是否等於先前的值。為此,值的類型必須符合
協議。Equatable
例如,如果您定義了一個平等的 Server
類型,該類型在其狀態更改時發布自定義通知(例如,從 signed out
到 signed in
),您可以使用任務修飾符將 Text
視圖的內容更新為反映當前選擇的服務器的狀態:
Text(status ?? "Signed Out")
.task(id: server) {
let sequence = NotificationCenter.default.notifications(
named: .didChangeStatus,
object: server)
for try await notification in sequence {
status = notification.userInfo["status"] as? String
}
}
此示例使用
方法無限期地等待由 notifications(named:object:)
實例給出的異步通知序列。AsyncSequence
在其他地方,服務器定義了一個自定義 didUpdateStatus
通知:
extension NSNotification.Name {
static var didUpdateStatus: NSNotification.Name {
NSNotification.Name("didUpdateStatus")
}
}
然後,服務器會在其狀態發生變化時發布此類通知,例如在用戶登錄後:
let notification = Notification(
name: .didUpdateStatus,
object: self,
userInfo: ["status": "Signed In"])
NotificationCenter.default.post(notification)
附加到 Text
視圖的任務從通知的用戶信息字典中獲取並顯示狀態值。當用戶選擇不同的服務器時,SwiftUI 取消任務並創建一個新的,然後開始等待來自新服務器的通知。
可用版本
相關用法
- Swift Optional task(priority:_:)用法及代碼示例
- Swift Optional tabItem(_:)用法及代碼示例
- Swift Optional tag(_:)用法及代碼示例
- Swift Optional textSelection(_:)用法及代碼示例
- Swift Optional toolbar(id:content:)用法及代碼示例
- Swift Optional tint(_:)用法及代碼示例
- Swift Optional toolbar(content:)用法及代碼示例
- Swift Optional textContentType(_:)用法及代碼示例
- Swift Optional touchBarItemPresence(_:)用法及代碼示例
- Swift Optional touchBar(_:)用法及代碼示例
- Swift Optional touchBar(content:)用法及代碼示例
- Swift Optional toggleStyle(_:)用法及代碼示例
- Swift Optional transaction(_:)用法及代碼示例
- Swift Optional textInputAutocapitalization(_:)用法及代碼示例
- Swift Optional touchBarCustomizationLabel(_:)用法及代碼示例
- Swift Optional truncationMode(_:)用法及代碼示例
- Swift Optional transformEffect(_:)用法及代碼示例
- Swift Optional touchBarItemPrincipal(_:)用法及代碼示例
- Swift Optional symbolVariant(_:)用法及代碼示例
- Swift Optional popover(isPresented:attachmentAnchor:arrowEdge:content:)用法及代碼示例
- Swift Optional mask(alignment:_:)用法及代碼示例
- Swift Optional listSectionSeparatorTint(_:edges:)用法及代碼示例
- Swift Optional badge(_:)用法及代碼示例
- Swift Optional fullScreenCover(isPresented:onDismiss:content:)用法及代碼示例
- Swift Optional keyboardType(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional task(id:priority:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。