-2

In swiftui, I have a presenter here,

class Presenter {

     @Published private(set) var viewModel: ContentViewModel

     @ObservedObject private(set) var viewModel: ContentViewModel
}

ContentViewModel conforms ObservableObject.

Which one is correct? Why?

BollMose
  • 3,002
  • 4
  • 32
  • 41

1 Answers1

1

First, it's likely that Presenter should be annotated as ObservableObject:

class Presenter : ObservableObject {

Secondly, when using a class like you say that ContentViewModel is, neither Published or ObservedObject is likely to have the effect that you're expecting.

In a View, @ObservedObject lets the View know to watch for updates to the @Published properties of an ObservableObject. When its objectWillChange publisher emits a new value, the View is re-rendered. But, your Presenter is not a View, so that's not applicable here.

@Published is used on an ObservableObject to create a publisher that will signal a View (see above paragraph). With value types (ie structs), the updates are sent automatically when the value changes. But, you're trying to use it on a reference type (a class), so updates won't get published automatically. Instead, you'll have to call objectWillChange manually when you update the object. See How to tell SwiftUI views to bind to nested ObservableObjects for more information on this and different strategies.

Without knowing how you'll use the Presenter it's hard to give advice about what path to take going forward.

jnpdx
  • 45,847
  • 6
  • 64
  • 94