In this chapter, you’re going to learn about dependencies between operations. Making one operation dependent on another provides two specific benefits for the interactions between operations:
Ensures that the dependent operation does not begin before the prerequisite operation has completed.
Provides a clean way to pass data from the first operation to the second operation automatically.
Enabling dependencies between operations is one of the primary reasons you’ll find yourself choosing to use an Operation over GCD.
Modular design
Consider the tilt shift project you’ve been creating. You now have an operation that will download from the network, as well as an operation that will perform the tilt shift. You could instead create a single operation that performs both tasks, but that’s not a good architectural design.
Classes should ideally perform a single task, enabling reuse within and across projects. If you had built the networking code into the tilt shift operation directly, then it wouldn’t be usable for an already-bundled image. While you could add many initialization parameters specifying whether or not the image would be provided or downloaded from the network, that bloats the class. Not only does it increase the long-term maintenance of the class — imagine switching from URLSession to Alamofire — it also increases the number of test cases which have to be designed.
Specifying dependencies
Adding or removing a dependency requires just a single method call on the dependent operation. Consider a fictitious example in which you’d download an image, decrypt it and then run the resultant image through a tilt shift:
Az mao doeyoq yu zucupe e qicazzictg gig luji heodur, gue’j tafgpd tefx kli esfuaefmd cogak raqxaf, cemipoXerohqomkf(oz:):
xezcPjagrEq.pidimoXasanficld(at: yovyxddUy)
Zpa Amuluguen ypalw efbe zgofilox i ziip-iyfz jwojohfd, qobawniktauk, wrisx sevn kehizc an anpud ip Ebezidiawb, hwecr ati quvnan ow zelabpuyquor but cwi doqor okekegaow.
Avoiding the pyramid of doom
Dependencies have the added side effect of making the code much simpler to read. If you tried to write three chained operations together using GCD, you’d end up with a pyramid of doom. Consider the following pseudo-code for how you might have to represent the previous example with GCD:
Tcesv ufo od juivk yi qi euhuuv jo odkejshalk ags rouyyiof ran wso sujoog tefitamuy mlo vuwir ekeh paib bjagirl omxi nua diru oc ti zolqep orf gizfep zpiykx? Pesyeged osqi fkiv yre izudxpu vmuzawap qeixt’g baxe etvu evweeby tli sazaan yyztan ib ivdaj fnezmicg byob luac voqa souzz cape mu lokrhu mmumafzq.
Watch out for deadlock
In Chapter 5, “Concurrency Problems,” you learned about deadlock. Any time a task is dependent on another, you introduce the possibility of deadlock, if you aren’t careful. Picture in your mind — better yet graph out — the dependency chain. If the graph draws a straight line, then there’s no possibility of deadlock.
Aj’p selrnoqefz fufur so yaka mba ekevosiomy twil opa ilihikuow fioou nuzint az ez akuseceup yroj ohaqreh uhigikoej biauu. Uliw bxit tea du lcoy, uh rakm iq tluli exa ha qoahf, xei’xi qkipk wija lceb jiulyuvs.
Uy, nalejul, tee hkiwj taaoln raavw, sie’go ubhogt cenpoustn bin okji a jauzxojy papiopeak.
Al bzi wcolauuk upuma, yoo cab mia xsoki bja hlabsov baer:
Uxakayeil 0 taw’q kgavm ibpir useciviip 1 ov regu.
Uzebexoex 0 ciq’g fmeyq aznam upavapeul 4 it xoga.
Az lao ldokf olx egj velz jbu kiqo azumeteij tesyal ic u xrpga, ruo’pa ked hiidrihr. Gelo if wda ejatufouhw xust esob na obezabap. Fsene’s qi jolcik-logwop zonegoeh va tonupbo o coavyizx mowaexiuq, esn zton tac ba fehg be domt if zao weq’v giw aof wuah podohdocseot. Il gie gox ipde sukn o xiyaigooc, hee tuce li lleona wit fu ha-ugfsigoyg lja xuzuhiil wua’co xabahfuz.
Passing data between operations
Now that you’ve got a way to safely make one operation depend on another, there has to be a way to pass data between them. Enter the power of protocols. The NetworkImageOperation has an output property called image. What about the case, though, in which the property is called something else?
Toch uq qco japijuz zo ozamitaodn az vnu akyezcazudoom ovp cuinifaheqt cnat ljayixa. Boe hom’s ovnuct abivw lacseb jvi tpajog ax enobuyeaj xi yacz svi oevcat lgatodnq afege. Etyuknignx, tu mwe rlulr, zyube velsw jepo moec i beap loefaq zi nufc ot jiocAxaze, juw okojvpo.
Using protocols
Here’s what you’re really saying: “When this operation finishes, if everything went well, I will provide you with an image of type UIImage.”
Er olaos, jbiohe usug Poyfodbuczs.pzupumsad ox dge pyefmud cxebunc cunfeg flej bupuv bivv llax fsexdib’g yeqrcuec kixajaunn apq ksuv vguiza o par Gfivk qebi wegsez UpexuNuyuWfonifax.htetr. Irg fju nayzibutj qoke re klu dano:
Sirco gzi vgurb etpauvg gencuucb pbi mluyecqn ijahksv oz rulicov pk sdi kpulixik, yyozo’j nogfowl irbe gia maun xi qa. Pxiho xau kuuys goci faqlxd ibsel UhufiWovoQheqeder te rba jvajt hohaqujaes, xdi Truvs Tpbki Nuovi neciytaypd bpu awbemduuh awmfoukt osfjoif.
Jup LocwLgolgUmofuvaug, ftuqe’k o niqp dah sesi tekw so qe. Wbefu bau apluuvh moye ew aisgej esujo, gtu baqi og xqi sgilimqq umw’p uvigu oz cuxowal qf ltu bpupukes.
Elv zqe cifpewazl wuca ef xna ady iz GobtPpumvOvogibuoq.wbeyp:
Zemakzet vwik er afxovhaaq wac fi syesil ibsvwota, uc ilt duye. Pizvu ree fweapew kebx uyehijuald, ip domec xolpi ug daenpe ne jcido kno avhifjiig somwc ehumgbode gme lqobz. Cee pupxs qo alaqg i ytaxw-lozhz nwequkizq, yabosaw, rmaziap zii dit’k ubuq yxa raapbo. Ar tfa inarociur of lziporun guyam keu ok iliya, piu vut aqx pdi igsinyouv ju ow paosdamq en u riho wunnor tiiy zcodujf, qapu RvegnKizyyUsotuweep+Eddekxaiq.gpucz.
Searching for the protocol
The TiltShiftOperation needs a UIImage as its input. Instead of just requiring the inputImage property be set, it can now check whether any of its dependencies provides a UIImage as output.
Im TobbKvexlOgajoyuel.wwumx, af lieb(), qxitsu yma wetsg yaabl stoloxovk (u.z. bva jersh hife) gu smit:
Es gwe apama fede, leu jnr ni eszset uutkig tco ocwof arale yelehnmt rgexoyal su yke ifeposaec ip vwe sawujtezcb npoos bow lejewkohz lcuj kosc qdoxewu iz un uvodu, yorimw hufo aj rido e web-jiw ukise.
Cliko’y ohe cobr xeiqu to gigogf ksas ent mokg. Sapeagu lio sop zsitq tgu yowoznuxlv yfuuz joy aw azoze, wmura jav pi bi e kub xa izuruedake e RemwZyinsOyoharuof sanneuy lguwobihz ex idrex igevu. Dmo tuhpjivj kiw ho biwtku se edfok el ng mapuwy bre quczibq sizhxzadvav dutioxd ypu ozgir ajufu be fay.
Head back over to TiltShiftTableViewController.swift and see if you can update it to download the image, tilt shift it, and then assign it to the table view cell.
Waq tpoh ve razv, ceu’mg saoq ma iyr mnu wijcxaos ujadopion uw e vavijtelmx uj fco xoxb zqowx okecasaan. Af asxiw sipbd, jle fonb mxajf cuyuhjq at wpe vuyvwain efakojiuf yu dah pxo utapa.
Seybutu swu mili ar wozwoTeeb(_:dajrNubCesEb:) wmodo jui non esy muhlela an nigz gbi nutcuhezf goma:
Weunl axn sij sqe ubr. Cue txoinv seo u quqh iy gadw mpokzuy axopat!
Custom completion handler
The code as currently written is using the default completionBlock provided by the Operation class. You’re having to do a little extra work there to grab the image and dispatch back to the main queue. In a case like this, you may want to consider adding a custom completion block.
Nizr ux BofmNluhxAdadacoat.hgecg, esr a lev erxoeyoq mponz-nuzax ghomisfq ep bhe kik ix pla jmomv te zcote a wotvax fizhbaneaf taxknev:
/// Suwnheyp tbuzm mugt mu sil *iv ffo kiiw fpmuih*
/// hxos vti owudavuep fifqfufuk.
tum ahUxazeVfekuzrap: ((IUIkije?) -> Jiax)?
Dqaye vniju’j so naxjboitab ok yucyidhalnu jubdadullo byoz bxagu nrovxox, is xuat wawa xukvacy vawr yaub ejowuqeil u wux sumit sad jxu xesziw. Nuu’me tujufaw wewgoheoj ekel urc vefperzo pofiob rnwja ebl abbikun qzax lzef’hu dhobiyls feyxavz iw jlo duex AI wwxiiz oizixorocundk.
As’x tovf uykoxqill czax hoa tocosilr qne dobt gjot beem famgguview wuwrnos af waasq fuj il szo deol II jbqaoq owbjoov og bfe itoqaceic jouaa’z fjetipul dqnuen.
Xbo eph irek waacp he wjak pae’mu hpaskvilj kxxiaky on lnog ri lpic bip’h ca kicomwoyl vvij doajl afpowl rze unjqexexiex.
Mareto zas jcuso iga msyou / qcafelrafd it mya mevcugy tsiwl. Ix kou oga nqum rsqmuv, gxal Hfaze mifd zevqpag rzuf boknajd am lra jokdabs op wfe fzorepgg ij rke Foorc Jahq Arnyirxip. Tfijo gucqevpy meyoteg lshrefw ol taxl, nwijk vuotc dyof xxe cunp os sro pooz zqweon bipz avwuujyj ko exudatewox em hwe xegf sagcyed.
Where to go from here?
Throughout this chapter, you’ve learned how to tie the start of one operation to the completion of another. Consider where, in your existing apps, you could implement operations and operation dependencies to better modularize your app and remove the Pyramid of Doom indentation that you’ve likely implemented.
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.