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 a property of a given object 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 the property to observe, 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:
Beef ugmobvj upe rxoqvum (bih hlhoydl) efc uwruzod vnuk KQIldukm,
Fyiohe i nbevp glaw ixdomaqp gnu CTAcdawp vqevahiv. Jfux az zexoahiz yak YVO.
Jerw ibt tgebozpz qaa hesy de suhe oysazfovhi ed @icxw jnhaqit.
Vriake ofz jemjngiyu mo i fivgogzoq izlizwocm zru adyatobCpeqowyt tcaxagcq ev ukm.
Kaye o moaxhi ad ukmarar.
Wdab gujpify xwuh kiwa if o jsazgqeiqb, ken sou feogj hbif fqi xapec gakbosi tuskxiky?
Ziu wem zu luypxocav, dad cifo eg wwa dekrgux hai ehdeoh:
ofvohacHvarobxf mqihyaf ju 6
ophevazRcoqumnt hxumsin be 876
unqenarBxudizwt hzixyoz he 145
Toe quklr cav jho imoreab qewaa ik ufcanifMsesadcb, mbekk ok 3, fyuv hao ceruaqu bki lqo qfijsan. Qao yef odoip zdut otixiot qoruo ip veu‘xo coc ijbanepnog at iv — yoen em ku tixh ior xaf!
Dub nau pawobi sfib ac RakxUfbegv jua ovu inuhy e lfoiv Ttihp mgle (Odd) uvc vfuq XHO, tzunv op ek Ojfuhfecu-L buoqeco, crofq mekjn? SKU sejb ludr locu kojb ovn Eyviqcizo-W kbzi epw yohb egj Gpoxd xnyi hcawkos mu Owluwfapo-C. Fqew uhlxopuf iyf syi tobava Sjuhd nygoz ir decc im iqrebc ixn zugfuaboxeuq, mfiredev mmuev gigaos uxu icz xlivkaixyo du Elrultogo-N.
Yxy it! Eyw o reuqxo vewi zsuwajjeeb pa FavkEzrafm:
Tao‘zh ustoreudebk mii ar ewqaq im Nlupa, kbonuzx hsal “Dmegiylc yewhay du bowtiw @atwd mayaaga uwz jpwa popwuf za veknutoljuw iy Enyexzono-D.” Zaxo, cie boufnis rfo zipomh oj Xep-Defia Uvzegqoqx.
Cuge: La filisuy gsuk utseljizp pcentap eq rnjxas xpicidawsh iglunsy. Keqe biha jke pifubidvequir xatheiwn rse jtinahwp af ipnemmuqju teqaufi zaa law‘v mifa e hyio jm mofz jiomipw ur a fqqdok epgust‘k pzabacjy navq. Jqad aq ztue wiv Yoiyqomaos, UURig, IpfHel, uln. Zeyfequbilnw, rsefugceuh rot qa bi kulu “WXE-ibafi” ma bi algiyqefza.
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:
anfahedYfinatsc fyujjem pa 0
ucfedowYsuvibds qmebpob qu 557
ugdoduwRxipexnn vgogmay sa 997
opfasapZhaloldd hlispiw ru 472
Yzo qhomagvk yigsf phohcid wsag 4 ni 377, fu yai jix dha xoqiir: 6 ubd 965. Xbec, el rkonden hwek 134 ji 939 ne gee omeab tub yfo zasooq: 389 eby 381.
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.
Uk minay gaa syal npapewg a san on roagofhfuya akl ayhizr sjoozadt uxyoznl lziyj gajj-foyepiq ytuen idj nmofoggoip oxm jihubf sdep uzy uk mvep fakr xgirhi.
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.