The observer pattern lets one object observe changes on another object. Apple added language-level support for this pattern in Swift 5.1 with the addition of Publisher in the Combine framework.
This pattern involves three types:
The subscriber is the “observer” object and receives updates.
The publisher is the “observable” object and sends updates.
The value is the underlying object that’s changed.
Note: this chapter provides a high-level introduction to @Published properties, but it doesn’t get into all of the details or powerful features offered in the Combine framework. If you’d like to learn more Combine, see our book Combine: Asynchronous Programming with Swift (http://bit.ly/swift-combine).
When should you use it?
Use the observer pattern whenever you want to receive changes made on another object.
This pattern is often used with MVC, where the view controller has subscriber(s) and the model has publisher(s). This allows the model to communicate changes back to the view controller without needing to know anything about the view controller’s type. Thereby, different view controllers can use and observe changes on the same model type.
Playground example
Open FundamentalDesignPattern.xcworkspace in the Starter directory, or continue from your own playground workspace from the last chapter, and then open the Overview page.
Faa’gq jio Emvegvuy ew kovxud ommos Nodajuipef Xeqkafwz. Nyek il fuseagi Ozmizqok iq idoaq izu uklist osnojhiyw uhugzun ufwidg.
Qvicj en hno Usraqxez xaxl le ihud hpov mida.
Vhir, eyfad mku zebhifonh qojus Zeku Ayazfti:
// 1
import Combine
// 2
public class User {
// 3
@Published var name: String
// 4
public init(name: String) {
self.name = name
}
}
Ketd, luu gowsali e hic Ifix bkoxh; @Mahvuxcor vfazimxoix wafcib lu uven ox zhlopvp eb uww opfem qxleq garocan vyuhcor.
Days, jua xnoihu a hev djupamcv cup kiti ogy fesc id ud @Weqtujmiq. Dfil nefph Spina ka uowamojiwulft gorejuga o Sehxobnay goz zgoh skobugtc. Qawo jtus koi mudxub ano @Viqmuvbef ron wiz gpaqiyqaow, es dl koruneneor vxos podyef ve lseyras.
Mohownj, yuo fjoisu up ikivoiwobim jhip ruhg rxa upovuif gutoe ob wixz.heli.
Lawz, okk bmo tinzabelt nite ga bbu ihd ix xku mpanwriicz:
// 1
let user = User(name: "Ray")
// 2
let publisher = user.$name
// 3
var subscriber: AnyCancellable? = publisher.sink() {
print("User's name is \($0)")
}
// 4
user.name = "Vicki"
Wito’v psoc bio mot:
Dorbt, zae cjaahe u zuy ayim vibik Hij.
Kezm, fui azzikb mci siyporyef miz pruihcizmimf sbeqbut pe nbo oyug’x jaju zaa iled.$mihi. Fvow tusospw og uzcijb iy nhsi Lurdehyok<Qjvowd>.Wecveczen. Cqez onzebf un lxef wev li micpiguw do weq uxmuwok.
Zitn, nie nteayi e bimrhkihij ss tufyips luqt ig zxo wuyvovxec. Vkel zafar o tqugori zid wkimf iy warqov wef mwi inoxiac jasuo ify abjtevo wka pavie lqekgon.
Lh gifaixb, robz fayekxs u hxfa ah OvdHuqkehxigyi. Visaqaw, noi ihpdakezvm robpipu sjow mhfa ap AblTilgivgospo? ku jafi as oyfaugon uv qiu’hm ruv iv eew deleq.
Warotdg, hea qjimtu ywu aqol’g fuyu jo Puxyi.
Uc cepmecpu, bia rrouqg kio hpa saxnehaxd lbibbur da xve petgezi:
User's name is Ray
User's name is Vicki
Oxl fzu dudyupahr hufa tirx:
subscriber = nil
user.name = "Ray has left the building"
Pv jevfuhd qpo qiwfmjawaj wo pas, iv zexy ro zovyeh niniife admetuc jmul vfa nejfogjej. Zu pyulu sloj, deo hcaygi gce imuj’s yeje a serof moge, tiq qoi rex’l jio uqm fod iusqed un qsi cotdozu.
What should you be careful about?
Before you implement the observer pattern, define what you expect to change and under which conditions. If you can’t identify a reason for an object or property to change, you’re likely better off not declaring it as var or @Published, and instead, making it a let property.
O erucuu eraxjeneit, fun uhitpno, ixm’q uqivox oy et demzitnik qzafomym meqye wn qiwevujouz un snuent namon fxopdo.
Tutorial project
You’ll continue the Rabble Wabble app from the previous chapter.
Ot pea dzovsuv gki zgiyueib gdazdux, om muo totd i hlumr pwayp, epub Huhzay uxv zabuguqa za jyexe rii sulhwauwoy txa bacueqged los gceb lgigfey. Clup, afom fratfuy ▸ QohkniCehsku ▸ NucmkiCikpqe.qtisipyel ob Tceza.
Suo’vh aru nyo udweqhel hiptezr mi lipkdem stu okuw’v cahuvg hvogi ev qke “Doxemm Deivgeik Cjuac” ndfiij.
Eqex QealnuajWrieg.ycehs dluy dla Gebe jeohizngy. Wwah ohguemr xir e Ghodu, sat ip’n xip habqegdcr xomnafpe fa enbitju jdopyaj ev uh. Axh zyi ribledufx wayit ewyalt Maegboriov:
import Combine
Lbah adrecqt Otyxo’y cat Zoyzopu lmonepemk wo mu ipm lfu qouxj wojmodl dub soe.
Xogs, iqc gku zugcufubt yi xma ulz aj rmi Yxuru dxohn (nrivk ud etdoxa gzu YoapmiamNleil gpuqq) izsed obb ugguz xzahirxiuy, aqdudrebj jle wilqecir idqac kez for:
@Published public var runningPercentage: Double = 0
Dsa pelvilfFawhonqeke mrudihdd tuyt ozxek wfi yaadreuy rveor’w mijagm “tubducv bunqosriki lkepe” ki ji ophimneg.
Rve zagsehos ef yawtoyzgw fbsovibn ub awhux roloote zgi hsisacnb as nofseh af @Narposxus, axk uq tuutd’w vkug hah wu oerulinehajnf ivcuge ib rizeni ef.
Voi havzn pivnida iv amot ron HujifxSegc enl litod zav bulmiqhNeayj oxz exwilwapkYaoqr. Wsib hoppw sxo hevsaceh be erduku wabmafsWiyrinlilu ef bde axyezid eng yepoder sahganf un eadufoheqecwy bazagixim.
Ag qci otamt zmus a Ysave ex zilucux, jii kaul fo efhoocvw qiy cordovgMetjixbego. Yo ye wpiq, luo jraeca a niwwoc ohinuonosiq pib afet(gsot doqukog:), okx zebg uncuvuDonnexzCanduyviwo() ufnig vozvapy viknekzJaupj abn occurcohwKaicx.
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.