Search code examples
swiftswiftuicombine

How to pass a @Published variable between classes using Combine?


I currently have an SDK that has a @Published boolean variable within a class (we can call this ClassA).

I'd like to expose this variable to an application (to use in SwiftUI), but not expose the entire ClassA. Therefore I have created a bridging class (BridgingClass) that will be exposed to the application without having to expose ClassA.

I have the following code. But it feels weird to use sink and manually change the variable based on the result.

@objc public class BridgingClass: NSObject, ObservableObject {
    var tmpVar: AnyCancellable?

    @objc public init (classA: ClassA) {
        super.init()

        tmpVar = classA.$hungryState.sink { val in
            self.isHungry = val
        }
    }

    @Published public var isHungry: Bool
}

How can I make the isHungry variable equal to hungryState from classA?


Solution

  • In order to do this, you can use the assign(to:on:) method. This replaces the sink method used.

    Basically the class would become:

    @objc public class BridgingClass: NSObject, ObservableObject {
        private var cancallables: Set<AnyCancellable> = []
    
        @objc public init (classA: ClassA) {
            super.init()
    
            classA.$hungryState.assign(to: \.isHungry, on: self).store(in: &cancallables)
        }
    
        @Published public var isHungry: Bool
    }