4

I wrote a very simple app to test Combine and the NotificationCenter:


extension Notification.Name {
    static let Test = Notification.Name(rawValue: "Test")
}

// SOLUTION 1
NotificationCenter.default
            .publisher(for: .Test)
            .sink(receiveCompletion: { _ in
                print("SOLUTION 1: COMPLETION")
            }, receiveValue: { _ in
                print("SOLUTION 1: VALUE")
            })

// SOLUTION 2
    NotificationCenter.Publisher(center: .default, name: .Test)
        .sink(receiveCompletion: { _ in
            print("SOLUTION 2: COMPLETION")
        }, receiveValue: { _ in
            print("SOLUTION 2: VALUE")
        })

// SOLUTION 3
NotificationCenter.default.addObserver(self, selector: #selector(doSomething), name: .Test, object: nil)

@objc
func doSomething() {
        print("SOLUTION 3: VALUE")
}

// RAISE NOTIFICATION

NotificationCenter.default.post(name: .Test, object: nil)NotificationCenter.default.post(name: .Test, object: nil)

Notifications aren't catched using Combine. The only solution working is the third one, the old-style one. The weird thing is that if I run the same code in the Playground, it works!

The deployment target for the project is iOS 13. I've executed the app on both a physical device and simulator. I've also installed iOS 13.2.2 simulator.

Any suggestion?

Luigi Trevisi
  • 81
  • 1
  • 7

1 Answers1

9

Don't forget to store your cancellable instance in a Set or variable. Example (using Set):

private var cancellableBag = Set<AnyCancellable>()

NotificationCenter.default
    .publisher(for: .Test)
    .sink(receiveCompletion: { _ in
        print("SOLUTION 1: COMPLETION")
    }, receiveValue: { _ in
        print("SOLUTION 1: VALUE")
    })
    .store(in: &cancellableBag)

Or using variable:

private let cancellable: AnyCancellable?

cancellable = NotificationCenter.default
    .publisher(for: .Test)
    .sink(receiveCompletion: { _ in
        print("SOLUTION 1: COMPLETION")
    }, receiveValue: { _ in
        print("SOLUTION 1: VALUE")
    })
Alex Zarr
  • 181
  • 1
  • 6