Combine Framework In Swift -3

Published Keyword

Publishing a property with the @Published attribute creates a publisher of this type. You access the publisher with the $ operator

@Published var heartRate: Double

When the property changes, publishing occurs in the property’s willSet block, meaning subscribers receive the new value before it’s actually set on the property

lets take an Example

class HealthMonitor {
@Published var heartRate: Double
init(heartRate: Double) {
self.heartRate = heartRate
}
}
let healthMonitor = HealthMonitor(heartRate: 90.0)
let cancellableObj: AnyCancellable?
cancellableObj = healthMonitor.$heartRate
.sink() {
print (“Heart rate recorded now: \($0)”)

}
healthMonitor.heartRate = 75.3

In the above example, the second time the sink executes its closure, it receives the parameter value 75.3. However, if the closure evaluated HealthMonitor.heartRate, the value returned would be 90.

Assign keyword:

Like in above example we can assign keyword to observe for change in value and assign it to a text

ex :

let title = UILabel()
Just(“How”)
.map{$0 + “are you”}
.assign(to: \.text, on: title)
print(title.text)

Output:”How are you” will be assigned to title

Note: Just : A publisher that emits an output to each subscriber just once, and then finishes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store