How to use async await with call to withAnimation?

Hello I have an async call that at the end of the call changes a state property value. I would like to animate that property change by using withAnimation. However withAnimation does not support async calls. Is there some other way of doing this?
I've included code that is something like what I would do, except this does not work. The error I get is Ambiguous use of 'init(priority:operation:)'

Button {
                        withAnimation {
                            Task(priority: TaskPriority.high, operation: {
                                disableCreateWalletBtn.toggle()
                                await createNewWallet()
                                disableCreateWalletBtn.toggle()
                            })
                        }
                    } label: {
                        AvatarView(90, image: UIImage(named: isDarkMode ? "wallet-dark" : "wallet-light")!, ringOn: true, isPadded: true)
                    }
                    .disabled(disableCreateWalletBtn)

withAnimation needs to synchronously capture mutations inside the closure, so you can't do any async work inside. By spinning up a Task you are not performing the mutations to disableCreateWalletBtn during the lifecycle of the closure you hand to withAnimation.

I believe the only fix is to localize withAnimation to be around each mutation:

withAnimation { disableCreateWalletBtn.toggle() }
await createNewWallet()
withAnimation { disableCreateWalletBtn.toggle() }
2 Likes
Terms of Service

Privacy Policy

Cookie Policy