6

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

0

2 Answers 2

9

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() 
}
Sign up to request clarification or add additional context in comments.

Comments

2

If your var property conforms to Equatable you can use the task(id:) modifier

VStack {
    Text("")
}
.task(id: var) { 
    await asyncFunction()
}

1 Comment

Keep in mind that this will call the function when the view initially appears as well, not only when the variable is changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.