Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a async function when a variable is changed

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

like image 403
Cenk Avatar asked Sep 08 '26 13:09

Cenk


1 Answers

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() 
}
like image 150
Nirav D Avatar answered Sep 10 '26 04:09

Nirav D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!