Difference between @ObservedObject and @StateObject

At first both look same. The @StateObject and @ObservedObject property wrapper tell a SwiftUI view to update in response to changes from an observed object (mostly viewmodel).

Both property wrappers require your object to conform to the ObservableObject protocol. This protocol stands for an object with a publisher that emits before the object has changed and allows you to tell SwiftUI to trigger a view redraw.

import SwiftUI

struct FirstView: View {
    
    // @ObservedObject var firstViewModel =  FirstViewModel()
    @StateObject var firstViewModel =  FirstViewModel()
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Counter - \(firstViewModel.counter)")
                    .padding()
                Button("Counter", action: {
                    firstViewModel.addsubCounter()
                })
                Spacer()
                NavigationLink("Next", destination: SecondView(getCounter: $firstViewModel.counter))
                Spacer()
            }
        }
    }
}


import Foundation
import SwiftUI

class FirstViewModel: ObservableObject {

    @Published var counter: Int = 0
    
    func addsubCounter() {
        counter += 1
    }
}

In above case both @StateObject and @ObservedObject property work exactly same. 

But when we call FirstView from another view and we update that view value of @ObservedObject get reset but value of @StateObject remain same.

import SwiftUI

struct MainView: View {

    @State var randomCounter: Int = 0

    var body: some View {
        VStack {
            Text("Random number \(randomCounter)")
            Button("generate Random", action: {
                randomCounter += 2
            })
            FirstView()
        }
    }
}

for @ObservedObject get 0 again when Mainview updated
for @StateObject value remain same even when Mainview updated

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s