neb
neb

Reputation: 145

SwiftUI: Why doesn't ObservedObject work in AppDelegate?

I've tried the example from the ObservableObject documentation.

class Contact: ObservableObject {
    @Published var name: String = "me"
    @Published var age: Int = 7
}

When I make a Swift Playground with the code:

let c = Contact()
c.objectWillChange.sink { print("This prints") }
c.age += 1

objectWillChange triggers and the line prints.

So far so good.

I now make a View in SwiftUI:

struct ContentView: View {
    @ObservedObject var contact = Contact
    ...

I create this View in the AppDelegate, and do:

   contentView.contact.objectWillChange.sink { print("This doesn't print.") }

I've connected the contact to various controls, and changing any fields updates all the controls. Doing onReceive(contact.objectWillChange) also works fine. But not connecting to it in the AppDelegate. I've tried logging deinit() to make sure we're talking about the same object. I've tried using ImmediateScheduler. No dice. Why is this not working?

Upvotes: 1

Views: 1003

Answers (1)

Sorin Lica
Sorin Lica

Reputation: 7656

When you create a subscription with .sink you have to save the AnyCancellable object returned

let cancellable = publisher.sink { ... }

And if you assign it to a variable, make sure it is not short lived. As soon as the cancellable object gets deallocated, the subscription will get cancelled too.

Upvotes: 2

Related Questions