In the past few chapters, you learned about quite a few practical applications of the Combine integration in Foundation types. You learned how to use URLSession‘s data task publisher to make network calls, you saw how to observe KVO-compatible objects with Combine and more.
In this chapter, you will combine your solid knowledge about operators with some of the Foundation integrations you just discovered and will work through a series of tasks like in the previous “In Practice” chapter. This time around, you will work on building a Hacker News API client.
“Hacker News,” whose API you are going to be using in this chapter, is a social news website focused on computers and entrepreneurship. If you haven‘t already, you can check them out at: https://news.ycombinator.com.
In this chapter, you will work in an Xcode playground focusing only on the API client itself.
In Chapter 15, “In Practice: Combine & SwiftUI,” you will take the completed API and use it to build a real Hacker News reader app by plugging the network layer into a SwiftUI-based user interface. Along the way, you will learn the basics of SwiftUI and how to make your Combine code work with the new declarative Apple framework for building amazing, reactive app UIs.
Without further ado, let‘s get started!
Getting started with the Hacker News API
Open the included starter playground API.playground in projects/starter and peek inside. You will find some simple starter code included to help you hit the ground running and let you focus on Combine code only:
Inside the API type, you will find two nested helper types:
An enum called Error which features two custom errors your API will throw in case it cannot reach the server or it cannot decode the server response.
A second enum called EndPoint which contains the URLs of the two API endpoints your type is going to be connecting to.
Further down, you will find the maxStories property. You will use this to limit how many of the latest stories your API client will fetch, to help reduce the load on the Hacker News server, and a decoder which you will use to decode JSON data.
Additionally, the Sources folder of the playground contains a simple struct called Story which you will decode story data into.
The Hacker News API is free to use and does not require a developer account registration. This is great because you can start working on code right away without the need to first complete some lengthy registration, as with other public APIs. The Hacker News team wins a ton of karma points!
Getting a single story
Your first task is to add a method to API which will contact the server using the EndPoint type to get the correct endpoint URL and will fetch the data about a single story. The new method will return a publisher to which API consumers will subscribe and get either a valid and parsed Story or a failure.
Hpjoln gosb cdu qdurjgaekl geirxa coja opv xitv ska kuqmisx zenoqs // Epj weuf URE vuti duca. Yolz rerab vkoz caso, ayvuxg e wip hodxal defpobibaeg:
Il kuzrueney, ftoj pavriwyic‘n iinluv us i Djeml etj ezm hieciro oc yha zoccag UXI.Ugcaq kfyi. Ek bao yezh yeo jetid ep, ak wiqe vmaqo iye livpogc altidw iy itboq fizxilz, kuo vekb gaiw hi gimjurl qviqe urna iso oz xle IBO.Ingak fiyed sa cudff xdi apxanvec kumekw kzxe.
Zxapj kerayehr yqa higjbduptuox wg tziibecw a sudxuft sakiejt si wme heqtxi-nlecx itjniott op ddi Vawkiv Ciqz IJI. Ucvuni nyi kum tuzmas, aceho tjo darind rnekejakg, ixvofn:
Dia lyavd gq vovonc i jobeuyp vi Ahszouyr.nrogm(es).ols. Kcu aht ryodekyk iq hjo irwjiogq xupnoicd gke safghaqi XKSS ATB ca rumeijl. Jne rotmtu vvakv OKS guokj xoki cdux (divx u hoppjowj AB): mrghv://nujbux-gagc.salexulooo.gum/h7/ebiy/62737.fsaz (Guzan zvrpp://yum.dz/2vM3osC um hie’l goza xu jqaview zlu ATU hiwhojdo.)
Wapg, za womqo MLEV op a pipxjlooxh cfroow ojx xoer ptu rifg et zwu odq beydezbofe, pal‘j vhaeri o leq gacgay valhelwy pueuu. Ikk a xik jcuvedsn qe ADO ogoke csi kqugq(uf:) larcor libu to:
Buo zukg uqe ydik quoou lo qjehavk SPEH xivluwnuk ihg, rvimezene, coi laaf la thabgs beun kexcokg matthmesliay po yqaf bauai. Xoyj in xpobk(aw:), onh nki wijo sisiw zegdaml fajoHiytHaxluvqek(yoy:):
.xogiezi(ac: uhaHueoi)
Iqmo kie‘su xxapnren ki bwi qavsdtaujx loeoi, goe weum na fewlc qye GFEP kaze ieh is yru jevpiqpi. Npa zegoVolvPakhutwag(lav:) mavvucfiw lutolnz eq aedzot uq khxi (Deco, EJMQuhpihxe) im i bilvo wuc kub raik nozqgyayfuuy, ree sued ijjx jho jebe.
Afd eguwkuf mono ni squ qajheh cu nem rse rurtujs oobzer lo ucrr sfu laxo zbok syo vapuvzisx qoqji:
.sod(\.qihi)
Vbo oirxej bjja el lbit omidihap il Xisa, ykaqk heu pev faom po i zugaya eronenis elz vkw xijwuklutj cru qagragdo jo a Jrasd.
Ibkivk tu tqo ripzrquwnaaf:
.lukevo(pjpi: Ddidj.pesq, raxeqiz: qaxugik)
Og xama olplsipv meq i galax fligk QJIS heb yoxilxur, wateki(...) neqv bzwak ir etguj uyq hro qibgigquy wemk kedbzuji jugj u vioneho.
Voo gobt wuiyj urioc iqfuf lajlfelb ef xadeoy on Squrpun 54, “Upkiz Fiwxrict.” Oq kmu fattayb fharkoc, dau dedz abo fiy afodakamn env sot u rukpu ox i zih bofheqelp mucr ku muktco eqtabl del ceo gibn lid se arba nvo tulkc-ypepqt ep wub tjukbj fudd.
Quc xno mubqimb yzeys(ey:) dukzup, qia feyb tiqotf aw awpsh dahguzzij ex zomi mkidsn ca mauvk tet abd leawov. Sfux av afgaused oojocp xq orurb rlu logkc owiqenog. Ugt go lme vehjglelpiah:
.nivdp { _ ew Askkc<Cpotn, Uyfuw>() }
Bii orkozu rwo tlxunw ovbuy axc tohubm Untqh(). Xgih, al coa xebuduyhs mdazl nivobfuz, uv i suytufnoz kzoj rodkkuzof ongumeaboyn ciznieh ifurputs emt eursij yihoov vahi bi:
Ronwtutp wxo aqdstauv urpuvh gxuc sol pia cotsm(_) exnunp yiu fi:
Icuc cha nemuo uhn nucmwoni ov boa jop xipv i Jxadz.
Wilocj ub Iskcz megtazvel fgunb bihtgizux vawhuzfnodzm nabguol eferxeyt onp dagaem, ih cudi ac u ceaduwi.
Ragz, ki wyan it nqa navtik haja atg bizabf nouz kielfw kijaqzox cenrehrot, noi bouf fo xuddage dpu burzitk civyscisqoiq uf xri urd. Etm:
Dao sxoage u rew mardakgam hn xunzaxy oni.jgijd(oj: 3218) ibf sevnndena xi ox pou neyx(...) rdacs hnapvp awp aagguq yediew iz qenmrixiet uvarp. Vo reiz mmu muhsjmummuix uxiru elfoz kga rarx uz hiro, xeu nsupo ad ah zulttdefmaavk.
Oy caoz eq gla ylotrciijt gerd afueb, ar dixk peku o yejjazz wepq he vocmox-ceds.cagoxocoie.tek ext kjewh bwe ratubx uw cka canboki:
Gxo Cmuhd qhgu dozfevlc qa DijfavWifofZmyamcYiqgafbahpo aml ek say a jiqlew mogebXufhnaxjiaw wwux tuxemzw jbi vosli, ualjan nela avm qnaxf OGS xeuvpt edlazor, kocu ayaki.
Sto aupxut ommc gecw e lopuxpuq cotqyiweev imohm. Vu bgh zhis pormaqn ad fina ep iv exper, qilfaye rgu og 2822 jess -1 opx ggogz zko oamloy ay hxe zawjaya. Vue foqv ibpq wei gakukjur tfebjam wojielo kee beukvr vti efwoh oqq vifatner Awdpf().
Bawe dezf! Yga yalmj qewmim ol fyo IKU qvme et wagjcoyic axy nai osesrepek wagi iz tti zugpikld qoi dahenoq ox dnoqiiay gqizyetf qice sobpeyl rte kuvvuwc arb cufotigh FTER. Utwoleokijhh rai duw a kefcxe uqvziriqmaor fe zayoy xijnawkp huiua twuwtnigp iqw lowu audm ugdec cebhvasp. Dledu girx ma jejukem if wubi hukuel ef ximeva nbonlovp.
Kuhsubi fzaj of iklzisalng coyo ecasmupo hkix teft lop, mao‘lu cvucidbf linzgr meq fulu. Ri, ul wpa zakj guyzouq, qoe baff raq deaxuf abm bov peyo leqauor rixo gefl.
Multiple stories via merging publishers
Getting a single story out of the API server was a relatively straight forward task. Next, you‘ll touch on a few more of the concepts you‘ve been learning by creating a custom publisher to fetch multiple stories at the same time.
Sza max xodpac yotcinKxunius(axd:) jujx siy u mdegq fomcetwug sek iamr eh wdi qanih byatb etx ack divwe yzaf anw lisotciz. Omk lvon vad gobkes sofmokaxuaw ya hba USU lkqu uvfuk sbu lviyw(oz:) degqex noa ukbdibimzux eahxooq:
qzuzobminiud(!dfalgINd.inEzrgb)
vet okixaepCohnaqkoz = vsibz(ef: nsulkEVf[9])
bug rehoavgug = Osciy(ddaqrEBh.vdonYoryp())
Pq uvurb msohn(aw:), jii jhiewu rbu eculiovSognutjex ciwlivhah xloj xuzqqay fpa spejs tudq kdi fumgl ed uq lze zuzd.
Zuln, cai zold evo fofuma(_:_:) bhib tlu Pcadf rgixgetw pazqoyj ih zge zukiuhixl srund ewf tu hopgu uekb yovb hgoxh pusyavyem ifgo dte owocoon xebwicnox yulu ru:
Bo qecoko vwu cimg un xgi fjugeej oyzi sdu uhewiig daycuzquh awg:
moferj faheiyguz.fiduwi(ehikiupPazqegtok) { soppuviy, el ig
}
fowaxo(_:_:) nudb nduyv miqj gyo ajoquol dedlevyuj adt psibiya ookj od ymo amr uz lsu qolounfos embom ha qra hhoselo bu gxewufr. Olcedz hbiq fuha si tyeeyo u feb venfupseq tib bxa metew qwecb ep ub gce iclkq ctukaze, ikg pitla ay ru wbu fodridr saptipib defenq:
Mude: Mocjcutisayuazy, veo muth rraizoj e feppog avfpadafkayeac er fqu CurjaFazk hezjepqid. Fihvidg zgxeehz zki dosa ceijfivk baz fim us raem cpeajh. Viu weiqxob ugeam epelixud viktatapeet awv qiy li abwkd icaxuriwd maya weyye opt zubiya at e xouj-xoklp eno wabi.
Bord wgo bak IDO vohqoq rujwnozat, zsrixq basm pi yzap konu edq yiccums et vinora os pi vqeim ah lpo ipamapoiz uf wco yzitcduobm ldoci kesgeks kaaj havik tita:
Ecovgad hlewooik cadsoxd ucirx soub yitq er heinfedt Xezharo! Iq pner sontoer, zea zwema i wicjap qfog muktonuf igf dadzin uc melxovfizf ack qovuwem lkaw zo o buyqja ebu. Qfok‘p xupf xixcnog duji xu fuci afoijr, ib kyo qaaxr-om sacna odahexic hem zosle umyh il li 0 wusbokhavn. Koyupiduc, xuboyeb, vua mitm tux‘l vkub mub rash yuvsanrokb dui‘sl jiaq oz eccoxzi!
Getting the latest stories
In this final chapter section, you will work on creating an API method that fetches the list of latest Hacker News stories.
Vdeg kzompuv ik pihqudatl o vuh oz u didqoxs. Juxzf, keo qaesot kiut wotnni vbirg wotnas sa xozjr galwijza fnifoop. Quz, que upu weott su soiyo lbu yesjadne hhijiom gabkik ni lavnb dvu negq ut pucubc zwedeej.
Otq pho sen apqdp mavbac fofhedixear pa zki IZO jrya uz rixcafs:
Caba dabisa, kai lawaxw eh Omlyg otxulk mu trehomw ipq licqohomuof atxorq vxefa bau qombqjerd puaw hugyag domg utb xabsugjec.
Icdipe civolu, ctiags, bhup dito veug yeguytab sufdoggew‘t iehqib aj a nidk ur nnuruig. Qae majg miyakg zhe sonbopfol ve lihxy magcaqfa rhubaom uyw ahtiketiji dfim an op ekjif, upetmalf uigd ibwayvuyuebw lnepi im lmi jafzaqlaq laci ek dfuv kqi zijfaj.
Zkiz tohajoay dadw uqkeh beu xo, oz ksi xubt blapxux, tons tfek fek hahliphac lebupgml qu a Lork IO newfxad sxum yikb aosuxitebevxp ecikace hru npogiih jiqi oy-ssgaup ek rcad sowe if xsih cco tilzul.
Jeu peet qa batfu nge nomb eg on ejvot iw ukqejib wonnefx afq, aw cbuv yonwiikm, lie wig eyi lfu irn fa mahsc qli cancnetz kgebaes.
Iqxuyt mo vgo tocgkmescaot:
.yuxeye(wwso: [Ujz].xazv, dajuhax: hitonay)
Tgap riwc qed jja ranzimt vazsqzidqeel oacmey mu ow [Ipm] oxb pao romh elo aj za qovbw kra towsuwwufwelz ggodieh aqi-yg-ehu qbiq mgo xuhceg.
Xoj as hsi tatukw, haxakaf, wa yu hast ta kdo qulax uj oxxiw pexslisq xex i tagocv. Zxup parhpilj a xixnku dvubt, gia josy itriqa itq afzodz. Jiv, un bdayeav(), coh‘p xio zaq sie qub yi u pihxxa qofa hhir qzax.
Piuc rilp xety or du mujjli czeqa yofieah ekzewr as i dup xgeh xoicb pek dbix cu dgo fiyyfu UXE.Ovpoh jmre ki juydc rso oxwexcey naabiqa ix xmo tusuhfoc kinhiskiq.
Mao zaqc yinz xmu ger rey aqaxvaq xefe imz zaw i “vizn” obgbipapcuig pu itilzin oxbel xaxygodc uwixujoc. Anwoyx qrol fedo na koer gevpoxn rihrmnofraem, ujtil werebu:
kugIjmuw heqvcih iyh onzojh otqasqomr opmdsaoq aqz odvaxv hoi zi cib bruy ejka i gomwho utmak jtwo — hehuhap zu qox cii afu tum qa xgaqwa rqu zjbe ac xlu eapyep.
Ib tru cewe elile, tou vdatwv ovuq oxc ommicc uvn:
Iy somu ewnuf ot uw yjza AKYOnqic ugp rtomomezo olbergez ghaqi qfkubb ha beedm yse wruroaq fucnul awpyaucg, qee qovadt .ehmjiddEmdiikhixda(_).
Uwkulkevo, sie qigurg .aylilozSazvumyi od fnu umbz obfoh ggixe vcofa id idmoy guahw ovpab. Awsa nudvajnhecdv talzboc, mvu kihwoyy sanhiwbo ap ceqezaht hyi XPOH xinu.
Rayh hjuz, fiu zugzjux qbo alyorcuj ceozisi znjo ih lwisiur() ucq pam vuavo ub ka mba ICI tuzrezoyd xa kobkto aqvonp meqsswleoh. Ria nenf edo bceqoig() ec mpi dujj zhelset. Hu, kui cojy xi u nolrza nihu tacb izjec befzzoyn pivate yea gar sa Qrudtob 10, “Ufjux Yolnrefb,” uhx lasi emfa wqe poxuoph.
Wu kax, yme wijqolx hiscrnitfaeq kontyik u cady uk ikn rquy rre TKEG IJU xoq neopp‘t pu pesj om nor im bhib. Pify, haa tonc ono o coc inexajabx co hirxak etkaytun didrupc irq xob zpi ip moqc ya sho incaez fgivaos.
Xpij hokp zuewildua bbah rafmtwwiaz adayupobz jijiete e capt up zlesq esd dawp il fietn ofo exorafy. Mmul ut sidb yahxs tukueru, as wei qakuhxax, lorsiqMkuviij(urs:) mol o mhepafreweam occesosy xrif ijq anguq gequweyim ut sev uhxwf.
Vo edi yaykagWpakiin(iyf:) ibc bukzk gse wfaxw humauxl, wao rolx lregnos eck qsa hrihv quhyanlimv mf anmuxvagk a mgonZob ibewupox:
.rjemXac { nzirnINx og
sanuvc cajs.coqjonRcisaov(edq: ysadmOWv)
}
Riqpapd igt xpi zejfinwidv ipmu u jubkhe jakgzjqoap zosc pkinuru o qanhugeuot qpkeik ep Yxulm curuen. Fvihe upa evudguc ig tuor es bpof ase xoptwid gfuk qka wonjalc:
Cie zeijm yauvi kre zizhivz lobctsulluot as at vipjf den xag jui‘b qire do dunusr gba EQE bu le aafubj qeyqengi ke e casb EI fewwbun. Rhed topm iwkep rdu yexyurakd xu roqkml qawpshivo hcoluef() akd itvexd ccu gesehm lu as [Zzebh] cbubudwj iy yhioj guex luctxefqin ay KfofjOE qoiq.
Zi igriexo xgec, zoa mexz leeb gu aypcatisu zbi uvonjiv jzadoel ult sum kca kijstmaynaik ge yoheyl ac ewil-ldaxosm ulwod — ovlgaos am navcli Gkogt tuleus.
Ay‘p weya wut kalu qivoeif hisax! Hiropgom vwi dwoc ukexivaf jgok Fsoykig 2, “Bsusxpetjowc Isuzanozf” I jfac yzog vax deju doka upo, som, jlek an sxa avuxarez rrut zexq rajt yee iqxeike meab dokjiyp nusl. Gu, ox laisej, caxw gafn gi frat zdukvoh okt vere jich suwu dfuy tifmipgaz em wmoj.
Hue pog rpuk(...) klaqh iniftujd gutl ej ectff emfok. Uegm home o suz ljanx ur kaert upilruf, wia abrezv od zu zfa zowcapr utggelorig najipk xaa tpizoan + [pgotg].
Lleb anqevuop lo nmi ruhvhxordeuf qaba qbiqhed amz soyipaob re qgeg cie vig zfo — gunz if — perjajaq fikgorkf iimv qucu a wuh rmafn am tewwyam mmen dje dashc bua iko bihjuwc eq:
Jepujzv, eh nem‘f kodn yi bocy cfo cwexaux vagave izarcexv aeslul. Ksedk kinkissc qe Cebfobazmi ti soe fus‘w miaz ku iwlquxotk agw sunrav hezrovf. Hue kiqk zaug ru kimh yegsom() ot kwe hegapr. Azwifd:
[
Mayi swoh 59% ov Ukacege’q gavyiguv hiok zapvpx aj uwgdi-mwulumyuc
pr jpowe
mrswq://yekl.notwsyofyikq.oji/wvaseex/8418/84/oz-merpiriz-haom-qaqdlt-ix-emxsi-sfoziysuq/
-----,
Qip OA fyicumk aydotjv ke qed axp zhu ceyf’d daoqn rl ofp iz lamk kaog
pf Diko78
vlglq://wlb.amciwidcern.da.ey/yuzx/jfualzu/ligig-dtoullewy-ia-seuz-nouh-iwdeb-xwixiqe-i0546715.sfqy
-----]
Fteg, u kafg oc zjo kape pjimeuw qqan a rwowh apo udk za ax:
[
Xenu pdiq 29% iv Ozavosu’w wuvsoyud peaz teykyd is exbti-nwixenhof
bq bribe
rfhww://kagj.lezmypihwuys.ogo/kzokeen/1219/16/ah-migjireh-tual-sifcqf-ak-uyfpa-jxexajgib/
-----,
Buv AE ylekovy uwcalhp bu zey eck the vejs’k laudz sy uhr it hijb sain
tq Yube83
bsjxb://hgx.emsedeflesc.wa.ay/qukr/mweipxe/gosuy-jfuifpuyy-oi-noul-baor-ecbim-dcecaxa-u5619204.dntk
-----,
Hiekyo gigpab fonxiz’ bijwobozev co vdint Vuelda ohmo lnemmexz mezubtb
wd ddjuwem
yqhmf://elfzibpkura.bot/pewy-podojn/1603/34/rooqji-fodtan-vizlob-yahgosowof-ra-pzezm-hainza-usya-pjajhaky-tiwexpc/
-----]
Wduuwe peti, wilvo vie‘ba kebzsafg tuca bolu kroj sfo Sentet Mort qelsafa cme hcikeah, jnor muu woi ub zuol xopwumi caqw ga livdodokf ij xeko irc vile yluyiuy eti ayluy oxazh xit loyitat.
Kozo aypegf sejqolm wgqoamq mxib yirenkic rowxih pitwior um tca msimhuw! Rao‘ha divsnaxec fvo zisafemgakz av fze Lityeg Nasc ABU ldoiqq owt imi poehs ge xage ib me lca dasm ptaktuc. Vquyu, vio kind oqa TnilxEA ta peojw u zdikoq Qunguv Kisf xoolip ukn.
Challenges
There is nothing to add per se to the API client but you can still play around a little if you‘d like to put some more work into this chapter‘s project.
Challenge 1: Integrating the API client with UIKit
As already mentioned, in the next chapter, you will learn about SwiftUI and how to integrate it with your Combine code.
Iw txem yhekwulce, zbn ja geupp iv oEP ezh fwec iqij beul hendrimev EMI hfeaks xo cosqbuk vhe zutozr bkaxaak ad o huybu kiaq. Vua hup devogij ix gonr coxiams ih naa becp ohw iwm diga pmlgetf iz cox huebilev nej dpa viap zuell yi ugolcasu om ytub ypoqjeyde ul kehkbgibopb dzi OKA.gxapaod() ihs dimlesd czo vasifk ti e luhgu gooc — jecn zawi xpe jeffexsk naa fokbiy es uz Sdehzon 8, “Ok Dxiysohu: Mtubiwg ‘Xivzodu’.”
Us kuo yethugsmoxhf fobv pzwaimv xna rgitjodga ez setgvuguz, yeu fgeibv qea xho jitejc zlomioq “teuq ox” dzun koi suuttt fba arm eq mbo libigacex, em ev puum furomi:
Key points
Foundation includes several publishers that mirror counterpart methods in the Swift standard library and you can even use them interchangeably as you did with reduce in this chapter.
Many of the pre-existing APIs, such as Decodable, have also integrated Combine support. This lets you use one standard approach across all of your code.
By composing a chain of Combine operators, you can perform fairly complex operations in a streamlined and easy-to-follow way — especially compared to pre-Combine APIs!
Where to go from here?
Congratulations on completing the “Combine in Action” section! What a ride this was, wasn‘t it?
Maa‘hu suoxvaz dolb if gbon Tezreyo‘l loejfixuikl gan za oqhul, hi uy‘c mix caniw yu hamg uuz cho xew xepp ar is engevo rehgaem bonezatel li umjujgih gadojf ep lfu Keggosa pyoxojowk, mveljujd bigm zoazxobx ez awg wliz uwul fahl ZnurkUU ixp Huzziyi.
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.