How to use async functions with WithAnimation

In my application, I query with @ModelActor. My goal in doing this is to perform the query operation in the background thread. I use .task(priority:) to display the queries. I want to use withAnimation inside the task, but as you know, it cannot be used with asynchronous functions. I'm waiting for your comments and ideas on how to do it. Thank you.

Answered by BabyJ in 788905022

Since you haven't provided any code samples, I can only guess at what you're attempting to do.

This code will work:

struct ContentView: View {
    @State private var fetchedData: [MyModel] = []

    var body: some View {
        List(fetchedData) { model in
            Text(model.name)
        }
        .task(priority: .background) {
            let data = try? await modelActor.fetchData()

            await MainActor.run {
                withAnimation {
                    fetchedData = data
                }
            }
        }
    }
}

It fetches the data asynchronously on a background thread, and then updates the UI with this new data, with an animation and on the main actor.


If this is not what you're looking for, or there is more to your issue, then you need to provide some more context and some code.

Accepted Answer

Since you haven't provided any code samples, I can only guess at what you're attempting to do.

This code will work:

struct ContentView: View {
    @State private var fetchedData: [MyModel] = []

    var body: some View {
        List(fetchedData) { model in
            Text(model.name)
        }
        .task(priority: .background) {
            let data = try? await modelActor.fetchData()

            await MainActor.run {
                withAnimation {
                    fetchedData = data
                }
            }
        }
    }
}

It fetches the data asynchronously on a background thread, and then updates the UI with this new data, with an animation and on the main actor.


If this is not what you're looking for, or there is more to your issue, then you need to provide some more context and some code.

How to use async functions with WithAnimation
 
 
Q