touchlab / KaMPKit

KaMP Kit by Touchlab. A collection of code & tools designed to get your mobile team started quickly w/Kotlin Multiplatform
https://touchlab.co/
Apache License 2.0
2.2k stars 199 forks source link

Use @StateObject instead of @ObservedObject to bind viewmodel to SwiftUI #250

Closed russhwolf closed 2 years ago

russhwolf commented 2 years ago

Using @ObservedObject would lead to bugs if the view also had @State properties, because changing the state would reinstantiate the viewmodel. This came up recently on a project where we stopped getting updates after a state change because the viewmodel was being recreated without calling activate() again.

TadeasKriz commented 2 years ago

Since this is KaMPKit, it might be worth adding the following link above it as a comment for people to dive into it.

https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject

image