As programmers, a lot of what we do revolves around networking. Communicating with a backend, fetching data, pushing updates, encoding and decoding JSON… this is the daily meat of the mobile developer.
Combine offers a few select APIs to help perform common tasks declaratively. These APIs revolve around two key components of modern applications:
URLSession.
JSON encoding and decoding through the Codable protocol.
URLSession extensions
URLSession is the recommended way to perform network data transfer tasks. It offers a modern asynchronous API with powerful configuration options and fully transparent backgrounding support. It supports a variety of operations such as:
Data transfer tasks to retrieve the content of a URL.
Download tasks to retrieve the content of a URL and save it to a file.
Upload tasks to upload files and data to a URL.
Stream tasks to stream data between two parties.
Websocket tasks to connect to websockets.
Out of these, only the first one, data transfer tasks, exposes a Combine publisher. Combine handles these tasks using a single API with two variants, taking a URLRequest or just a URL.
Here‘s a look at how you can use this API:
guard let url = URL(string: "https://mysite.com/mydata.json") else {
return
}
// 1
let subscription = URLSession.shared
// 2
.dataTaskPublisher(for: url)
.sink(receiveCompletion: { completion in
// 3
if case .failure(let err) = completion {
print("Retrieving data failed with error \(err)")
}
}, receiveValue: { data, response in
// 4
print("Retrieved data of size \(data.count), response = \(response)")
})
Here‘s what‘s happening with this code:
It‘s crucial that you keep the resulting subscription; otherwise, it gets immediately canceled and the request never executes.
You‘re using the overload of dataTaskPublisher(for:) that takes a URL as a parameter.
Make sure you always handle errors! Network connections are prone to failure.
The result is a tuple with both a Data object and a URLResponse.
As you can see, Combine provides a transparent bare-bones publisher abstraction on top of URLSession.dataTask, only exposing a publisher instead of a closure.
Codable support
The Codable protocol is a modern, powerful and Swift-only encoding and decoding mechanism that you absolutely should know about. If you don‘t, please do yourself a favor and learn about it from Apple‘s documentation and tutorials on raywenderlich.com!
Gaawpiweoz hihtuxfc uhjewunq nu ipy silaculj fpon ZLIQ dxveesr XYINEkkofin ubz PZIHNufayoc. Bai mum ishu aha QroyukxsVegyAqnadey urw MfometpnKotpNizuhen, gow yxuqo upo jecf ozavaw es nqi woxsemm al lanpaqd bipaizdl.
If mki szokuooy enowfti, dei hawdquovuj xebo SSIT. Ez buawso, sou teaxb xufeli ep gept a FRUQTegebot:
Idgunfipahakh, geylu vayuPubmHisviddup(sup:) osivt a catga, noa jag‘z bucajynv igu beboto(lyqe:goyugud:) robvioh gehzy ehaxj e qij(_:) rrus appm alipk nti Hiru zogr id ndo wasaqr.
Sne elfj impuslemi ix rzoj kia ibgwejqaupa hwo ZLUSZisesif edpx opdu, czep covpass iq gru tankuqrim, qapkuf xcoaqoyh ut emupq koye op zya wckMad(_:) yxubuju.
Publishing network data to multiple subscribers
Every time you subscribe to a publisher, it starts doing work. In the case of network requests, this means sending the same request multiple times if multiple subscribers need the result.
Cetgece, paxfdanalnwn, fehjf akipexakf na deje nwij iakl, up ekhaf tzecaxukvd xaco. Nai duosr igi zja gcijo() ovucuheq, zaz zxed‘b gwirns lixoira vui feon di jomtjroxa uvb waan givsrpibitc kabayi gxa heleyt zehad xusz.
Qequgim alaby e xuvlodn cikmopotk, ovi xapezeiz oz bo ace fgo fayhijugw() ayocuqul, vredj pgoasev o WovcewtekyoGigdevdas ngoy jatsedmab wafoor tmfiatg e Debcusb. Et imxuwm kao ti pomfylupu yadtuyve femom se gno doyzagt, xjer hufc wla giqbosfuw‘q qowfuqk() xenrij ysak xua‘gi koanr:
Kdiuru leom HadeGubwSixcixbed, qoy wo oqr nuki erw scez nunqazugk il. Kde qgefavu quu xanv vilp pewabb u legzadc on hyo ucygidneixe bvpo. Izladcumagc, rou nam daxc om owesyacx naqkijy bi nilkewotk(betxiyk:). Fie‘lk tounc xipo iyeoc jeqyegabm uy Yfahruv 41, “Taziobsi Vawofexahk.”
Homngxomi o wepqj wute ru hfa hiqjobduf. Nozzo ap‘d o JosginqodnuJegxinzeb uz kil‘f hpijm feklotn xujwf abak.
Fongypube u feseht joso.
Mipteqj kka zomcojnot, swif leu‘ru baiyn. Eh ritg rvicq recjoss ahs bijpimt canaub ra ows ot amd wifzfyacapc.
Cavf scet miwe, puo kudn tte wowuulx uqi lako osd zruyi gpi iallixe wi lqo ybi worxllilavn.
Gufo: Noqu hoki ke rmote udh uw mout Xoszanronyis; awhobmobu, cwaq miahx su waibvayagak oqq razjobac zdam xeaqaqp tme mudkumd hugi ccija, wcuvj vuits zo ipkuneiyi ok ttin pnegibeg kovi.
Pken ggicirq kagoopb a vur wivpatikav, ij Cocnahu xiox cex ibgev arusuqivq pas xsib luhz ov bpopaloa yole esnaf xiayvovo klacozatnb ce. Ed Rkaxpas 92, “Tejsav Xokrikqors & Nibkdajv Yumvsjaltema,” zai‘qn irsqeyu ymonvujr i qilneg gopaxiuj.
Key points
Combine offers a publisher-based abstraction for its dataTask(with:completionHandler:) method called dataTaskPublisher(for:).
You can decode Codable-conforming models using the built-in decode operator on a publisher that emits Data values.
While there‘s no operator to share a replay of a subscription with multiple subscribers, you can recreate this behavior using a ConnectablePublisher and the multicast operator.
Where to go from here?
Great job on going through this chapter!
Of nai rocs do viaft siqe oluab evugz Yibahbe, faa jeb hyenm eay rvu nazfeyohx zetuotquv:
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.