Call a async function when a variable is changed (SwiftUI)
Asked Answered
E

1

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

Ebenezer answered 13/9, 2022 at 8:38 Comment(0)
P
8

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() 
}
Paunchy answered 13/9, 2022 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.