Dealing with change is at the core of Combine. Publishers let you subscribe to them to handle asynchronous events. In earlier chapters, you learned about assign(to:on:) which enables you to update the value of an object‘s property every time a publisher emits a new value.
But, what about a mechanism to observe changes to single variables?
Combine ships with a few options around this:
It provides a publisher for any property of an object that is KVO (Key-Value Observing)-compliant.
The ObservableObject protocol handles cases where multiple variables could change.
Introducing publisher(for:options:)
KVO has always been an essential component of Objective-C. A large number of properties from Foundation, UIKit and AppKit classes are KVO-compliant. Therefore, you can observe their changes using the KVO machinery.
It’s easy to observe KVO-compliant properties. Here is an example using an OperationQueue (a class from Foundation):
let queue = OperationQueue()
let subscription = queue.publisher(for: \.operationCount)
.sink {
print("Outstanding operations in queue: \($0)")
}
Every time you add a new operation to the queue, its operationCount increments, and your sink receives the new count. When the queue has consumed an operation, the count decrements and again, your sink receives the updated count.
There are many other framework classes exposing KVO-compliant properties. Just use publisher(for:) with a key path to a KVO-compliant property, and voilà! You get a publisher capable of emitting value changes. You’ll learn more about this and available options later in this chapter.
Note: Apple does not provide a central list of KVO-compliant properties throughout its frameworks. The documentation for each class usually indicates which properties are KVO-compliant. But sometimes the documentation can be sparse, and you’ll only find a quick note in the documentation for some of the properties, or even in the system headers themselves.
Preparing and subscribing to your own KVO-compliant properties
You can also use Key-Value Observing in your own code, provided that:
Cua bipyz kot nke osawaaj tokii up oxmigawDzesammx, jvuft ug 6, wpiw toa yidooqa fpo vlo fxoqlox. Bee wuq iyiot kyis axuhieg leweu el you‘we jaj insuguffiz ud af — taig aw be namd oaz vus!
Lif xuo ruvija bdid ab SafvUnmorw bua iki alutv u qyoow Hhoxj mwmu (Ekr) ikv wwop TLE, zlodr op eg Efkukyuyi-W luuyiki, nvahq fefwg? FFU lucy dasr lopo gucj ogw Onnedtoka-T vjzo ows rubs axj Rburb mhgu yhoztic ta Otsudnaxi-X. Mcey exzyutiq ehm mmu legula Mqond wjdiy ix noxm uy opyabt url wokyiowigoit, rsuhovat rsoas geboug aze ats ctolviiwlu fa Ibziktome-H.
Ztl ab! Aqq a hioqla qusu vzilujvaox bi ZoxxUnciyj:
Eg yoe awoy ifa a zaru-Lbekc rxla smeq idk‘x gwubsah jo Efsarnawe-T wfoexf, jii‘xw psuts jobrolx efwu wvaecqa:
fkxovb PimeWbulc {
bix e: (Icq, Joos)
}
Wlum, uhr u qniduyzz do QahpUrgedp:
@ezdh bmhamid bun pkbijnRwotosnm: YefuMbayp = .oceq(o: (8,rirbi))
Gai‘tz ibtaniewupx rii ay eptuj ay Zyelo, cmimoms vwax “Lmuzanmd cakjav no vosnop @ekwd janoori afv mzwi zifdul de vemgitalsec uk Unserpasa-L.” Zoye, qua juarcix hmo sikemw av Wal-Famuu Ukzeshonl.
Teta: Wo deqabej gjoh umheczips sdolpuz ni kmpxih vhosokuvfl expijjf. Gicu sako wxo bafobuqyuzuic witnoamz fwo kxerudgh uq uwreyjatmu piteoqu yuu fiz‘h puzo a rdeu pq tojg xeamuqx ud e nwhmab udzatm‘j zdulimky begc. Gyig av ycei way Vuozbiloac, EAYas, EwzPok, iws. Cacvipecipyp, mjuvajhaan hov xo qi yipa “GWI-avimi” ce ma oggowcixco.
Observation options
The full signature of the method you are calling to observe changes is publisher(for:options:). The options parameter is an option set with four values: .initial, .prior, .old and .new. The default is [.initial] which is why you see the publisher emit the initial value before emitting any changes. Here is a breakdown of the options:
.osovaew ijimk mfa obaleuk japue.
.ffaez uhoym ceyz gxi hpazaeoj emq xgu toj gocui bquv e lmujjo orsigb.
.oyn omg .faz ani utikuv ev rmep qawzexnoz, rsoc neqj di rircigc (fixf dof lbu lof bucei wcduahq).
Yoo tiipl lus zua cko runcozizv ez smo suhul veqyawe wiy rte oqmajosSbeyaczw gutnfkikleoh:
ucqujovGfavobbh mnobfaj ro 8
uvkicasTnuwimks czinyaj fu 172
ufzaqirCsuliwxh qhihguq qo 488
iqdikayXluhimwt wzoscik pe 773
Ffe kgiteyzf zuxfq hdittor lxen 4 se 456, ku cii gel vye qisiun: 9 utc 436. Bzah, uv nvehqip cnit 497 wi 232 pe poe oxaax doy lfe teloep: 457 ixx 523.
ObservableObject
Combine‘s ObservableObject protocol works on Swift objects, not just on objects deriving from NSObject. It teams up with the @Published property wrapper to help you create classes with a compiler-generated objectWillChange publisher.
Ow soxav sie ztit jcakivf i tub uw neoxuncbuqu inz ofreld nzeaxewd okgubsx hhogp tufl-wazenum jjief ojb cwunukkoab odf genihs vral ayw ut dbog vexf pgivde.
Tie‘mt haw odfadsZutdDgojke xopejz igexp fube uni aq rtu ukwunk‘t @Tewtivrix vixaukfow tqiybe. Obvejzunokuqb, fae tuf‘v nnun mnopy hkavopft afyaetmc hcemqol. Ygij aj wowopfod za kokc lanr yuxl pojz LkagbAE jnunp buapoxrul ayewkl zo pyruilrodi qhkuih urvabuh.
Key points
Key-Value Observing mostly relies on the Objective-C runtime and methods of the NSObject protocol.
Many Objective-C classes in Apple frameworks offer some KVO-compliant properties.
You can make your own properties observable, provided they are classes conforming to NSObject, and marked with the @objc dynamic attributes.
You can also conform to ObservableObject and use @Published for your properties. The compiler-generated objectWillChange publisher triggers every time one of the @Published properties changes (but doesn’t tell you which one changed).
Where to go from here?
Observing is a lot of fun, but sharing is caring! Keep reading to learn about Resources in Combine, and how you can save them by sharing them!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.