How can I animate changes to an @ObservedObject?

It looks as though using withAnimation inside an async closure causes the color not to animate, but instead to change instantly.

Either removing the wrapping asyncAfter, or removing the withAnimation call and adding an animation modifier in the body of your ContentView (as follows) should fix the issue:

Color(viewModel.color).onAppear {
    self.viewModel.change()
}.animation(.easeInOut(duration: 1))

Tested locally (iOS 13.3, Xcode 11.3) and this also appears to dissolve/fade from blue to red as you intend.


Using .animation()

You can use .animation(...) on a body content or on any subview but it will animate all changes of the view.

Let's consider an example when we have two API calls through the ViewModel and use .animation(.default) on body content:

import SwiftUI
import Foundation

class ArticleViewModel: ObservableObject {
    @Published var title = ""
    @Published var content = ""

    func fetchArticle() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
            self?.title = "Article Title"
        }
    }

    func fetchContent() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
            self?.content = "Content"
        }
    }
}

struct ArticleView: View {
    @ObservedObject var viewModel = ArticleViewModel()

    var body: some View {
        VStack(alignment: .leading) {
            if viewModel.title.isEmpty {
                Button("Load Article") {
                    self.viewModel.fetchArticle()
                }
            } else {
                Text(viewModel.title).font(.title)

                if viewModel.content.isEmpty {
                    Button("Load content...") {
                        self.viewModel.fetchContent()
                    }
                    .padding(.vertical, 5)
                    .frame(maxWidth: .infinity, alignment: .center)
                } else {
                    Rectangle()
                        .foregroundColor(Color.blue.opacity(0.2))
                        .frame(height: 80)
                        .overlay(Text(viewModel.content))
                }
            }
        }
        .padding()
        .frame(width: 300)
        .background(Color.gray.opacity(0.2))
        .animation(.default) // animate all changes of the view
    }
}

The result would be next:

Animation modifier on body

You can see that we have animation on both actions. It might be preferred behavior but in some cases, you may want to control each action separately.

Using .onReceive()

Let say we want animate the view after first API call (fetchArticle), but on the second (fetchContent) - just redraw view without animation. In other words - animate the view when the title received but does not animate view when the content received.

To implement this we need:

  1. Create a separate property @State var title = "" in the View.
  2. Use this new property all over the view instead of viewModel.title.
  3. Declare .onReceive(viewModel.$title) { newTitle in ... }. This closure will execute when the publisher (viewModel.$title) sends a new value. On this step, we have control over properties in the View. In our case, we will update the title property of the View.
  4. Use withAnimation {...} inside the closure to animate the changes.

So we will have animation when the title updates. While receiving a new content value of the ViewModel our View just updates without animation.

struct ArticleView: View {
    @ObservedObject var viewModel = ArticleViewModel()
    // 1
    @State var title = ""

    var body: some View {
        VStack(alignment: .leading) {
            // 2
            if title.isEmpty {
                Button("Load Article") {
                    self.viewModel.fetchArticle()
                }
            } else {
                // 2
                Text(title).font(.title)

                if viewModel.content.isEmpty {
                    Button("Load content...") {
                        self.viewModel.fetchContent()
                    }
                    .padding(.vertical, 5)
                    .frame(maxWidth: .infinity, alignment: .center)
                } else {
                    Rectangle()
                        .foregroundColor(Color.blue.opacity(0.2))
                        .frame(height: 80)
                        .overlay(Text(viewModel.content))
                }
            }
        }
        .padding()
        .frame(width: 300)
        .background(Color.gray.opacity(0.2))
        // 3
        .onReceive(viewModel.$title) { newTitle in
            // 4
            withAnimation {
                self.title = newTitle
            }
        }
    }
}

The result would be next:

Useing onReceive

Tags:

Swift

Swiftui