简体   繁体   中英

SwiftUI: Why doesn't ObservedObject work in AppDelegate?

I've tried the example from theObservableObject 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM