我正在开发 SwiftUI 视图。视图中有一个按钮,当我们按下按钮时,应该执行两个操作,一个用于执行动画,另一个用于异步 API 调用。我想知道哪一个更好。 (想象performAction应该发生在viewModel中,我们无法将动画与API调用分开)
查看:
Button {
withAnimation {
viewModel.performAction()
}
} label: {}
视图模型:
func performAction() {
state = .edit
Task(priority: .background) {
await fetchData()
}
}
或:
查看:
Button(action: viewModel.performAction()) { }
视图模型:
@MainActor
func performAction() {
withAnimation {
state = .edit
}
Task {
await fetchData()
}
}
在 SwiftUI 中使用 async/await 是
.task
或 .task(id: isRunning)
,例如
@Environment(\.myController) var controller
@State var isRunning = false
@State var result: Result<[Item], Error> = .success([])
...
Group {
if case let .success(items) = result {
...
}
}
...
Button(isRunning ? "Stop" : "Start") {
isRunning.toggle()
}
.task(id: isRunning) { // runs on appear, cancels on disappear, restarts on change of id.
if !isRunning { return }
do {
let items = try await controller.fetchItems()
result = .success(items)
}
catch {
result = .failure(error)
}
isRunning = false
}