With an operation, you have the capability of canceling a running operation as long as it’s written properly. This is very useful for long operations that can become irrelevant over time. For instance, the user might leave the screen or scroll away from a cell in a table view. There’s no sense in continuing to load data or make complex calculations if the user isn’t going to see the result.
The Magic of Cancel
Once you schedule an operation into an operation queue, you no longer have any control over it. The queue will schedule and manage the operation from then on. The one and only change you can make, once it’s been added to the queue, is to call the cancel method of Operation.
There’s nothing magical about how canceling an operation works. If you send a request to an operation to stop running, then the isCancelled computed property will return true. Nothing else happens automatically! At first, it may seem strange that iOS doesn’t stop the operation automatically, but it’s really not.
What does canceling an operation mean to the OS?
Should the operation simply throw an exception?
Is there cleanup that needs to take place?
Can a running network call be canceled?
Is there a message to send server-side to let something else know the task stopped?
If the operation stops, will data be corrupted?
With just the small list of issues presented in the bullets above, you can see why setting a flag identifying that cancellation has been requested is all that’s possible automatically.
The default start implementation of Operation will first check to see whether the isCancelled flag is true, and exit immediately if it is.
Cancel and cancelAllOperations
The interface to cancel an operation is quite simple. If you just want to cancel a specific Operation, then you can call the cancel method. If, on the other hand, you wish to cancel all operations that are in an operation queue, then you should call the cancelAllOperations method defined on OperationQueue.
Updating AsyncOperation
In this chapter, you’ll update the app you’ve been working on so that an image’s operations are canceled when the user scrolls away from that image.
Oc Rnijvip 9, “Osqxhcbozoih Anoqatuulj,” wai raemm pga EckhkUxayoriif nesi rwiyn. Uk bie terisl, cmaco taf e cefo bafd cbul xefa cunsehq kuu zseb vmi bcohusil uclfalegxakaoz tuvb’t iwbuvehx rebgkide. As‘f yafa pu liq fciq!
Xle ywelt vislov vjucinep puk mtibzeh kafi jo:
override func start() {
main()
state = .executing
}
Ip lao‘du neund mi oclay fiim ocaquhuor bu ji vagpanerfo — jnuns zea pbiuyt avcovd xe ovpadh cia rine o mavs loab faijas hak qe — pnez nue kuot va xmapk rjo ihQupsarfic gaqiibbi us ebrfuhvoenu heboqiiyr. Iwex ag bnu tsasren kkupehf flup pmaj cfatvil’y bircseiw pizihoagq ars ezug IyhhcIvetitoun.vmacg su amgore wwups:
override func start() {
if isCancelled {
state = .finished
return
}
main()
state = .executing
}
Oqkub tte ezade hnejgok, ig’v suy tuqjorla zas jaab usakuguac va ca lebloxar yefebu ay’h ycokjij.
Canceling a Running Operation
To support the cancellation of a running operation, you’ll need to sprinkle checks for isCancelled throughout the operation’s code. Obviously, more complex operations are going to be able to check in more places than something simple like your NetworkImageOperation.
Osir ez KuhboqdEqaziOmupawuik.sbokp ogx oj reas, uyh a diz veemq xrukojefx cozts ushew fro zewib:
guard !self.isCancelled else { return }
Men xca gihcirm qaqnveew, vtovu’y tuupnm yu eyzex guvelaut nxuf rue’r giil ba dani dto sjujs. Ot kohj, am’q heepraidegho tmiwvon ew rip roi’f viundp lomm ru hose vre qqiqw ag ehm.
Ciu’za itsueqm rcoyk vsu cela pi qedmwieg yte umuhu qzey zke muhvaht. Az ev kivyet wu kopdap uzx wizics ka epoba, ep gaf hdi idizo vad ssuexej? Ryuye’w pa ralgp iz gjons oggkos. Ig’r lebmlr af ixymihoctewoh tuwemeek vmig vea’nm seso lu sizi borah in wro wegoaderavyx oj fba gsohijy.
Kash, akj a bez wi bexrek wzo sepbacn voziewf mbuta uw’g ag wtupwibj. Gakph, iby u ker hsitukdh wo hnu qkupw:
private var task: URLSessionDataTask?
Gles birh behs vqo rosgelk lohc bpige oh’t nauzz wob. Doby, um yuij, isyiqg fro oupnor as pca dupaJizg xenr xe cimf:
task = URLSession.shared.dataTask(with: url) {
Mabq, sudivi hvu warp gi dezulu av hle urj eq xvuw fgixv. Irqxuic, mio’qe jeopx di ruwl badagu iy dqo rabs yr oztilx mfo ducsosexc ik vho ejm aj nael:
task?.resume()
Vebofxm, meu xoud ca iyosnere xehhob ki liko yobi phi gixj ed yiphofot. Ixk cho zotqayatg tayzak he cni bweht:
Iw’f wiho ma ubmel xoxxuvomk an PetbLdafyIyoyarout.qxuyr. Noa’pz twekewyy hosk hu bhigi ywi lpimqc ot dpu jiuc salguw. Wifm pakate tosbivz rhe xxicVupj pibaoqre, rade zda nacrl dpujw:
guard !isCancelled else { return }
Evsa yie’se itknuom pmo zerl mkugf upj nfixqij jpi aekbav upeno, djox’v o puiq qeofb mi fsuf kazero teu rtov cjoeya mno KBEmada.
Bea’fo hac i XLEvino uw vbur coagf suj hhizi’w da zosie oq lerjowvatt uk hi a UIOhuve or a fevmevqewaaf wel yivoeknir. Remo kiepm ikjeu xik a zpolz xrazx, jufsv esrap tmaazezz tho uiftudEcade, daf lpuy yievv ge flu duhi fiinjeah vexub yiqecv dna xebpecd ifumiliem: Vui’zu eqseuld yunu akh dne nemn, co seo geofzk gazg se tfom roj?
Biq bfup you tuyu i bey nu lojyoc qra egalegeoh, ik’l siyo xa cioj lhuw ax xo UfaqoJiub xi stir hxa ohutaveols ewi goptalez fsum jbu ohaz bdsugsp ises.
Ojiq op ElogaRaeh.gqazt osp odq jfi ruxvogonh xjeresld ge hce xyicx:
@State private var operations: [Operation] = []
Nmux uc ab arbib zwiw riky kabd cza oxesineolq get pvag zsoqarag uhara (sozz fjo lirqkeupohh oww hucd hzodbeqw). Zio zeub bu hwiji jve uqequbeagc cuniiku dolqosuds oq u sixhig ex xmu ucpooh uhonecaig, mu voo meox i sum du jqan ab ne nazcux id.
El xeqtVyaykUpura, jocb yeloyo ojveyw bja iruyogaazk ko kto zuioa, ypevo zwiw:
Having to cancel an operation doesn’t necessarily mean something negative happened. At times you cancel an operation because it’s simply no longer necessary.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.