Combine ObservableObject in UIKit

I began messing with combine in one of my personal projects and I am trying to use combine to allow my controllers and views to subscribe to different values in my app state.

I created an app state that has @Published properties, and that’s great, I can subscribe to changes on those properties, but in the case of a controller wanting to subscribe to the entire app state, it seems as though the option is only ObservableObject My confusion arises in the fact that this protocol exposes objectWillChange and not something like objectDidChange. Which means when I add a sink to it, I’m only ever getting the old value of state instead of the most recent. Am I missing something? Is this there a better way that I’m not aware of?

You're not really missing anything here - it's a very focused API endpoint (that I believe was meant to support some of the internals/optimizations of SwiftUI - but I'm asserting that with no detailed knowledge).

the objectWillChange publisher's Output type is type-aliased to Void, so while you'll get a triggered notification, it's also not actually passing any changed values - just the notification that the referenced object was, in fact, changed (or is about to change) in some fashion - so that your code can open up that object and inspect it for what it is after the change.

Hello connor.

objectWillChange would publish before set newValue. and Ouput = Void
so, you can not access newValue.

But, you can access newValue next dispatching after change operation.

      .sink { [weak self] in
          DispatchQueue.main.async { [weak self] in

this code will print oldValue and newValue.

Terms of Service

Privacy Policy

Cookie Policy