Search code examples
swiftcombine

Detect Boolean toggle of @Published property with Combine?


I have the following published property on my view model in Swift:

@Published var myBool = false

I would like to have a trigger that fires only when myBool toggles.

How would I do that using Combine?


Solution

  • You need to create a subscription to your published property but you need to make sure you droop the first value to make sure it is only triggered for when the value toggles.

    private var cancellables = Set<AnyCancellable>()
    @Published var myBool = false
    
    // ...
    
    init() {
        $myBool
            .dropFirst()
            .sink { newValue in
                print(newValue)
            }
            .store(in: & cancellables)
    }