I have a @State
variable and async function. I want to call the async function whenever that variable is changed.
Basically, what I am trying to do
VStack {
Text("")
}
.onChange(of: var) { newValue in
await asyncFunction()
}
But this gives me the following error
Cannot pass function of type '(Int) async -> ()' to parameter expecting synchronous function type
CodePudding user response:
You cannot directly call an async function in the synchronous function. You need to wrap your call in Task
or else you need to declare your function as async
. Now in this case you cannot make your onChange
action async
so you need to wrap your call with Task
.
Task {
await asyncFunction()
}